Writing a Windows service is the same as writing a Windows application. Some callback functions must be filled in and registered with the Windows Service Manager. Otherwise, the service cannot be started. I have recently written a service, and I have encountered some problems. I 'd like to share some content with you. please correct me.
The general framework code for Windows Services is as follows:
# Include <windows. h>
# Include <tchar. h>
Void winapi servicehandler (DWORD dwcontrol)
{
Switch (dwcontrol)
{
Case service_control_stop:
{
Exitprocess (0 );
}
Break;
}
}
DWORD winapi threadfunc (pvoid PV)
{
Sleep (2*1000 );
Return terminateprocess (getcurrentprocess (), 1 );
}
Void winapi servicemain (DWORD dwnumservicesargs, pstr * ppcserviceargvectors)
{
Service_status_handle hservice = NULL;
// If the following is not initialized, the Service Manager cannot receive the message
Service_status srvstatus = {0 };
Outputdebugstringa ("Service Main .....");
Hservice = registerservicectrlhandlera ("winservice", servicehandler );
Srvstatus. dwservicetype = service_win32_own_process;
Srvstatus. dwcurrentstate = service_running;
// The Service accepts the stopped control. If you do not want others to stop your service, the following line of code can be deleted:
Srvstatus. dwcontrolsaccepted = service_accept_stop;
Setservicestatus (hservice, & srvstatus );
// This sentence is also very important. I didn't have this sentence at the beginning, and the service cannot be started.
Createthread (, threadfunc, 0); // The thread is just an example. After 2 seconds, the service automatically exits after it is started.
Return;
}
Int _ tmain (INT argc, _ tchar * argv [])
{
Service_table_entrya scarrtable [] =
{
{"Winservice", servicemain },
{Null, null}
};
Startservicectrldispatchera (scarrtable );
Return 0;
}
The above instances are for reference only.
You can use the following command line to register the compiled EXE:
SC create "windowsservice" binpath = "windowssrv.exe" // when the binpathpattern symbol is used, the system cannot register the service. Change windowssrv.exe to the full path of your own exe.