写了一个监控服务的程序,共享上来,大家共同学习一下.网上找了很久,没什么收获,就自己写了一个.
CMonitorServiceDlg *g_pDlg = NULL;
DWORD WINAPI MonitorServices(LPVOID lpParameter)
{
char serviceName[128];
memset(serviceName, 0, sizeof(serviceName));
sprintf(serviceName, "Data Acquisition Service");
SetDlgItemText(g_pDlg->m_hWnd, IDC_SERVICE_NAME, serviceName);
SC_HANDLE schSCManager = NULL, schService = NULL;
SERVICE_STATUS ssStatus;
DWORD dwOldCheckPoint;
try
{
schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (schSCManager != NULL)
{
schService = OpenService(schSCManager, serviceName, SC_MANAGER_ALL_ACCESS);
if (schSCManager != NULL)
{
while (true)
{
if (QueryServiceStatus(
schService, // handle to service
&ssStatus) ) // address of status information
{
if (ssStatus.dwCurrentState == SERVICE_STOPPED)
{
StartService(schService, 0, NULL);
Sleep(20000);
}
}
}
}
}
}
catch(...)
{
}
if (schService) CloseServiceHandle(schService);
if (schSCManager) CloseServiceHandle(schSCManager);
return 0;
}
上面只写了一个线程代码,这个是主体程序.
1.schSCManager = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
打开服务控制管理.
2.schService = OpenService(schSCManager, serviceName, SC_MANAGER_ALL_ACCESS);
打开指定服务,获取服务句柄.
3.QueryServiceStatus(schService, &ssStatus)
查询指定服务句柄的状态.
4.CloseServiceHandle(schService);
关闭服务句柄.(与线程一样)
阅读(1716) | 评论(0) | 转发(0) |