感谢 songtzu.
服务程序的编写可以参考:https://www.cnblogs.com/songtzu/p/3543920.html
服务的启动
从服务程序到服务正真运行起来,可以分为两步。一,创建服务;二,启动服务。
创建服务,通过CreateService(***)可以在服务数据库中建立一个新的服务项,还会在注册表生成相应的数据。如果创建成功,可以通过任务管理器查看新建服务。
注册表数据:
任务管理器:
启动服务,服务创建只是生成相应的“配置”数据,服务程序还没有正真运行起来。在之前的基础上调用StartService(***),就可以启动服务了。
完整的启动服务过程:
void LanuchService(char* BinPath)
{
char ServiceName[] = "MemoryStatus";
SC_HANDLE hSCManager = NULL,hService=NULL;
SERVICE_STATUS ServiceStatus = { 0 };
hSCManager=OpenSCManagerA(NULL, NULL, SC_MANAGER_ALL_ACCESS);//0XF003F
if (hSCManager)
{
hService = OpenServiceA(hSCManager, ServiceName, SERVICE_ALL_ACCESS);//0XF01FF
if (hService)
{//服务已经创建
printf("Service:%s is created!\n", ServiceName);
if (QueryServiceStatus(hService, &ServiceStatus))
{
if (ServiceStatus.dwCurrentState == SERVICE_STOPPED)
{
printf("[+++]service is stopped,let's get it running!\n");
if (StartServiceA(hService, NULL, NULL))
{
printf("service is running now!\n");
}
}
}
}
else
{
//printf("OpenService fails,error is 0x%x\n", GetLastError());
if (ERROR_SERVICE_DOES_NOT_EXIST == GetLastError())
{//服务没有创建
hService=CreateServiceA(hSCManager,ServiceName,ServiceName,SERVICE_ALL_ACCESS,
SERVICE_WIN32_SHARE_PROCESS,SERVICE_DEMAND_START,SERVICE_ERROR_NORMAL,BinPath,
NULL, NULL, NULL, NULL, NULL);
if (hService)
{
printf("[---]service is created!");
if (StartServiceA(hService, NULL, NULL))//启动服务
{
printf("service is running now!\n");
}
else
{
printf("start new service fails,error is 0x%x\n", GetLastError());
}
}
else
{
printf("CreateServiceA fails,error is 0x%x\n", GetLastError());
}
}
}
}
else
{
printf("OpenSCManagerA fails,error is 0x%x\n", GetLastError());
}
if (hService)
{
CloseServiceHandle(hService);
}
if (hSCManager)
{
CloseServiceHandle(hSCManager);
}
}