ACE service configurator configures dynamic services

Source: Internet
Author: User
Tags protected constructor
1. Export DLL creation steps

For more information, see <ace programmer guide> P25 and DLL creation. On this basis, add 6 and 7

1) Specify the DLL name, for example, agentservice (. dll)

2) generate_export_file.pl agentservice is used to generate the custom agentserviceexport. h header file.

3) The source file of the main function of the DLL project contains the agentserviceexprot. h header file of the program.

4)When declaring a class, insert the keyword agentservice_export between the class keyword and the class name.
Note: This keyword is not required if it is a DLL project.

5) when compiling the DLL source file, define the macro agentservice_build_dll

6)Add the following macro to the DLL source file:
Ace_factory_define (agentservice, agentserver)
AgentserviceIs the DLL name, And agentserver is the name of the specific implementation class in the DLL

7) Compile the SVC. conf file for calling the exe. The format is
Dynamic agentservice service_object * agentservice: _ make_agentserver () "agentserver. xml"

2. How to create the caller exe

1) For the console, the main function provides the following examples:

#include <WINSOCK2.H>#include <atlbase.h>#include <ace/OS.h>#include <ace/Object_Manager.h>#include <ace/Service_Config.h>#include <ace/Service_Repository.h>#include <ace/Service_Object.h> #include <windows.h> int main(int argc, char* argv[]){CoInitialize(NULL);    ACE::init();       ACE_TCHAR path[MAX_PATH];    ACE_TCHAR cwd[MAX_PATH];     ::GetModuleFileName(GetModuleHandle(NULL), path, MAX_PATH);    //LogEvent(path);    ACE_TCHAR* ptr = path + ACE_OS::strlen(path);    while(*ptr != TEXT('/') && *ptr != TEXT('//') && *ptr != TEXT(':')){        --ptr;        if(ptr == path) {            break;        }    }    *(++ptr) = '/0';     //::SetCurrentDirectory(path);     ACE_OS::getcwd(cwd, MAX_PATH);    ACE_OS::chdir(path);     int argcSvc = 4;    ACE_TCHAR *argvSvc[4] = {        ACE_TEXT("OnmiService"),        ACE_TEXT("-d"),        ACE_TEXT("-f"),        ACE_TEXT("svc.conf")    };//  argv[3] = path;    if(ACE_Service_Config::open(argcSvc, argvSvc) == -1) {        ACE_DEBUG((LM_ERROR, ACE_TEXT("start ace_service_config failed/n")));    } while(1){        cin >> ch;        if(ch == 'q' || ch == 'Q')        {            ACE_DEBUG ((LM_INFO, ACE_TEXT (" | %t | %N %l | Stop OnmiConsole!/n")));            ACE_Service_Config::fini_svcs();            break;        }}    CoUninitialize();    return 0;}

2) if it is an MFC-based dialog application, you need to create a first-line startup DLL

m_pConfigService = DYNAMIC_DOWNCAST(CConfigService, AfxBeginThread(RUNTIME_CLASS(CConfigService)));    if(m_pConfigService == NULL)    {        AfxMessageBox("Start Agent Service failed");        return -1;    }class CConfigService : public CWinThread{}

For the implementation of cconfigservice, refer to the Configservice. h and Configservice. cpp files in the agsd project.

/// // Configservice. h # pragma once // cconfigservice class cconfigservice: Public cwinthread {declare_dyncreate (cconfigservice) protected: cconfigservice (); // dynamically create the protected constructor virtual ~ Cconfigservice (); Public: Virtual bool initinstance (); Virtual int exitinstance (); Virtual int run (); bool stop (void); file * getoutstream (); bool m_isrun; protected: declare_message_map () PRIVATE: file * m_out ;}; //////////////////////////////////////// //// // /// Configservice. CPP: implementation file // # include "stdafx. H "# include" agsd. H "# include" Configservice. H "# include <ACE/OS. h> # include <ACE/Object _ Manager. h> # include <ACE/service_config.h> # include <ACE/service_repository.h> # include <ACE/service_object.h> # include <ACE/reactor. h> // cconfigservice implement_dyncreate (cconfigservice, cwinthread) cconfigservice: cconfigservice (): m_out (null) {} cconfigservice ::~ Cconfigservice () {} bool cconfigservice: initinstance () {ACE: Init (); errno_t err = freopen_s (& m_out, "freopen. out "," W + ", stdout); If (Err! = 0) {afxmessagebox (text ("redirection error! ");} Return true;} int cconfigservice: Run () {ace_tchar path [max_path]; ace_tchar CWD [max_path];: getmodulefilename (getmodulehandle (null), path, max_path); // logevent (PATH); ace_tchar * PTR = path + ace_ OS: strlen (PATH); While (* PTR! = Text ('/') & * PTR! = Text ('//') & * PTR! = Text (':') {-- PTR; If (PTR = path) {break;} * (+ PTR) = '/0 ';//:: setcurrentdirectory (PATH); ace_ OS: getcwd (CWD, max_path); ace_ OS: chdir (PATH); int argcsvc = 4; ace_tchar * argvsvc [4] = {ace_text ("onmiservice"), ace_text ("-d"), ace_text ("-F"), ace_text ("SVC. conf ")}; If (ace_service_config: open (argcsvc, argvsvc) =-1) {ace_debug (lm_error, ace_text ("START ace_service_config failed/N");} m_isrun = true; return ace_reactor: instance ()-> run_reactor_event_loop ();} int cconfigservice: exitinstance () {freopen ("con", "W", stdout); Return cwinthread: exitinstance ();} begin_message_map (cconfigservice, cwinthread) end_message_map () // cconfigservice message processing program bool cconfigservice: Stop (void) {ace_reactor: instance ()-> end_event_loop (); Return 0;} file * cconfigservice: getoutstream () {return stdout ;}

3. Explanation 3.1. Description of project establishment

1) if it is a DLL project and has a dllmain entry function, you do not need to export and declare the agentserver class;

2) Only projects transformed from the console, and there is no main function or dllmain function, you need to export the declaration of the agentserver class, the Declaration symbol is agentservice_export, use the $ ace_root/bin/generate_export_file.pl agentservice command to export the specific symbols (agentservcie is the DLL name)

 

3.2. Macro ace_factory_define (CLS, service_class)

Description of the macro ace_factory_define (agentservice, agentserver)

Agentservice is: CLS-is the identifier used by the Program/library to import/export declarations. It depends on the parameters passed in when the export header file is generated using the above command, and the parameters are consistent.

Agentserver is: service_class is the name of the class derived from ace_service_object. It will be instantiated during service initialization and the name of the class to be exported must be consistent internally.

 

3.3. configuration file SVC. conf

SVC. conf format

Dynamic ident service_object * Lib-pathname: factory-func () [active | inactive] [parameters]

Instance

dynamic AgentService Service_Object * AgentService:_make_AgentServer() "AgentServer.xml"

Here, agentservice is the identifier and can start with another name.

Agentservice indicates the DLL name

_ Make_agentserver () indicates the name of the implementation class in DLL.

"Agentserver. xml" is the parameter name

4. Example

Getting started with Ace dynamic service configuration in Visual C ++
Abstract:
Dynamic service configuration has obvious advantages in writing server applications. This article briefly introduces the use of visual C ++ (7.1)
Write the ace dynamic service step.
This article applies to beginners of ACE.

1. Main Process

1.1 create a main program
Use Viusal studio to create a Win32 console project named glivr86serviced. Note:
D Indicates daemon, not debug. This project will be transformed into nt_service in the future (subsequent steps will be introduced.
1.2 modify project attributes (configuation properties)
1.2.1 Add the main file glivr86serviced. cpp to the project. The objective is to add the C/C ++ option to the project properties.
1.2.1 General modify program output path $ (outdir)
1.2.2.debugging command arguments:-D, started in debug mode
1.2.3 C/C ++ settings
1.2.3.1 additional include directories/I [path]: $ (ace_root );
1.2.3.2 code generation:/MTD;/MTD for mt debugging and MT for release
1.2.3.3 Preprocessor: preprocesor definitions/D: Win32; _ debug; _ console;
This is the debug version. Change _ debug to ndebug.
1.2.4 link settings
1.2.4.1 input: additinal dependencise: ACE (d). Lib. for debugging, select aced. Lib,
Select Ace. Lib for the release.
1.2.4.2 system: subsystem/subsystem: Console; (/subsystem: Console)

Main program code

// @ File: glivr86serviced. CPP // @ Description: IVR 86 main program entry of the business service // @ Author: jiangtao // @ version: 2.0.0 # include "stdafx. H "# include <memory> // use auto_ptr # include" ACE/OS _ns_unistd.h "# include" ACE/tp_reactor.h "# include" ACE/reactor. H "# include" ACE/service_config.h "# include" ACE/thread_manager.h "// static ace_thr_func_return event_loop (void * Arg) {ace_debug (lm_info, "(% p | % T), event_loop ()/n"); ace_reactor * reactor = static_cast <ace_reactor *> (ARG); reactor-> owner (ace_ OS :: thr_self (); reactor-> iterator (); Return 0;} int ace_tmain (INT argc, ace_tchar * argv []) {const size_t n_threads = 4; ace_tp_reactor tp_reactor; ace_reactor Reactor (& tp_reactor); auto_ptr <ace_reactor> delete_instance (ace_reactor: instance (& reactor); If (ace_service_config: open (argc, argv) =-1) ace_error_return (lm_error, ace_text ("% P/N"), ace_text ("open"), 1); ace_thread_manager: instance ()-> spawn_n (n_threads, event_loop, ace_reactor: instance (); ace_thread_manager: instance ()-> wait (); Return 0 ;}

2. Create a dynamic link library for the loaded Service
2.1 use Visual Studio to create a new project glivr86service. We still open it from the blank Win32 Console
Start
1.2.1 Add the main file glivr86service. cpp for the project. The objective is to add the C/C ++ option to the project properties.
1.2.1 General: configration type: changed to dynamic link library dynamic library (DLL)
1.2.3.1 additional include directories/I [path]: $ (ace_root );
1.2.3.2 code generation:/MTD;/MTD for mt debugging and MT for release
1.2.3.3 Preprocessor: preprocesor definitions/D:
Win32; _ debug; _ windows; ace_build_svc_dll
This is the debug version. Change _ debug to ndebug.
Note that the ace_build_svc_dll macro should be added here. If generate_export_file.pl is used
Generate a custom export header file. This macro can also be customized.

2.2.2 linker settings
2.2.2.1 input: additinal dependencise: ACE (d). Lib. Select aced. Lib for debugging,
Select Ace. Lib for the release.
2.2.2.2 system: subsystem/subsystem: Console; (/subsystem: Console)
2.2.2.3 General, output file:
../Glivr86serviced/glivr86serviced/glivr86serviced. dll

Enter the path or environment variable path in glivr86serviced
To facilitate debugging.

2.2.2.4 Adanced, import libaray: $ (outdir)/glivr86serviced. Lib
The above is the debug version. The release version can remove the suffix D, that is
$ (Outdir)/glivr86service. Lib

3. service dynamic link library implementation

3.1 add two files for the project to declare and implement Service Factory respectively
// @ File: servicefactory. h
// @ File: servicefactory. cpp
The Code is as follows:

// @ File: servicefactory. h // @ Description: IVR 86 Business Service // @ Author: jiangtao // @ data: 2006-7-3 // @ version: 1.0.0 # ifndef servicefactory_h # define servicefactory_h # include "ACE/svc_export.h" # include "ACE/service_config.h" # include "ACE/service_object.h" // declare servicefactory_t) class ace_svc_export servicefactory_t: Public ace_service_object {public: // initializes object when Dynamic Linking occurs. virtual int Init (INT argc, ace_tchar * argv []); // terminates object when dynamic unlinking occurs. virtual int Fini (void); // returns information on a service object. virtual int Info (ace_tchar ** info_string, size_t length = 0) const ;}; # endif/* servicefactory_h *//******************************** ********************************** // @ File: servicefactory. CPP # include "servicefactory. H "# include" ACE/log_msg.h "// implement servicefactory_t int servicefactory_t: Init (INT argc, ace_tchar * argv []) {ace_debug (lm_info, "(% p | % t) Service initialization completed/N"); Return 0;} int servicefactory_t: Info (ace_tchar ** STRP, size_t length) const {ace_debug (lm_info, "servicefactory_t: Info ()/n"); Return 0 ;}int servicefactory_t: Fini (void) {return 0 ;}

5. service configuration file SVC. conf
Dynamic ivr86service service_object * glivr86service: _ make_servicefactory_t () Active

6. Running result

5. Another example is to configure dynamic services.

The more powerful functions of the ACE service configurator framework are now configured for dynamic services. If you receive instructions at runtime, the dynamic server can dynamically load data from the shared library (DLL. This capability allows you to replace services at runtime to provide great flexibility.

The ACE service configurator framework simplifies all redundancy work. We only need to implement the services we need according to the design specifications, load them into a dynamic link library, and edit the configuration file. In other words, we only need to create a dynamic link library that meets the specifications, and then the SVC in the above example. add one or two lines of commands in the conf file and run the program again to load the dynamic service. We don't even need to re-compile the program.

Dynamic Link Library mydll

5.1. Make sure that the dynamic link library we will design is named mydll5.2. run $ ace_root/bin/generate_export_file.pl mydll and write the output to mydll_export.h.

Design the class of our service, include the file in the class source file, and

#i nclude “Mydll_Export.h” class  Mydll_Export MyDynamicObj : public ACE_Service_Object {public:       MyDynamicObj();       virtual ~MyDynamicObj();        virtual int init (int argc, ACE_TCHAR *argv[])       {              printf("MyDynamicObj::init------/n");              return 0;       } virtual int fini()       {                      printf("MyDynamicObj::fini-----/n");              return 0;       } }; ACE_FACTORY_DEFINE(Mydll,MyDynamicObj)
5.3. Compile and add the following command in SVC. conf before running the command. It is found that the dynamic service has been loaded and removed.
dynamic MyDynamicObj Service_Object* Mydll:_make_MyDynamicObj() "" remove MyDynamicObj

Tip: http://blog.csdn.net/badmouse/article/details/3993439

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.