Text: General framework for writing Windows services using the C language
just as you write Windows services and write Windows applications, there are some callback functions that must be filled in and registered with the Windows Service Manager (Service Manager), or it will cause services to fail to start. Because recently wrote a service, which encountered some problems, some of the content would like to share 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;
Service Manager cannot receive messages if the following is not initialized
Service_status srvstatus = {0};
Outputdebugstringa ("Service main ...");
Hservice= Registerservicectrlhandlera ("WinService", Servicehandler);
Srvstatus.dwservicetype = service_win32_own_process;
Srvstatus.dwcurrentstate= service_running;
The service accepts stop control, and if you don't want someone else to stop your service, the following line of code can be removed
srvstatus.dwcontrolsaccepted = Service_accept_stop;
SetServiceStatus (Hservice,&srvstatus);
//This sentence is also very important, I just started without this sentence, resulting in service cannot start
CreateThread (0,0,threadfunc,0,0,0); //thread is just an example, after 2S, the service automatically exits after startup
Return
}
int _tmain (int argc, _tchar* argv[])
{
service_table_entrya scArrTable[] =
{
{"WinService", ServiceMain},
{null,null}
};
Startservicectrldispatchera (scarrtable);
return 0;
}
The above examples are for reference only.
You can register the service with the compiled EXE using the following command line:
SC Create "Windowsservice" binpath= "Windowssrv.exe" //"binpath=" This equals sign has a space, otherwise cannot register the service, please Windowssrv.exe Change to your own EXE where the full path.
General framework for writing Windows services using the C language