檢測指定名稱的服務運行狀態,若服務暫停則恢復服務,若服務停止則啟動服務。 BOOL DetectService(
char* ServiceName)
{
SC_HANDLE hSC = ::OpenSCManager( NULL, NULL, GENERIC_EXECUTE);
if( hSC == NULL)
{
return false;
}
// 打開服務
SC_HANDLE hSvc = ::OpenService( hSC, ServiceName,
SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
if( hSvc == NULL)
{
return false;
::CloseServiceHandle( hSC);
}
// 獲得服務的狀態
SERVICE_STATUS status;
if( ::QueryServiceStatus( hSvc, &status) == FALSE)
{
return false;
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
}
ofstream outfile;
outfile.open(".\\檢測結果.txt",ios::app);
//服務已啟動
if( status.dwCurrentState == SERVICE_RUNNING)
{
outfile<<"服務";
outfile<<ServiceName;
outfile<<"已啟動 \n";
return true;
}
//如果處于停止狀態則啟動服務
if( status.dwCurrentState == SERVICE_STOPPED)
{
outfile<<"服務";
outfile<<ServiceName;
outfile<<"處于停止狀態 \n";
// 啟動服務
if( ::StartService( hSvc, NULL, NULL) == FALSE)
{
return false;
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
}
// 等待服務啟動
while( ::QueryServiceStatus( hSvc, &status) == TRUE)
{
// ::Sleep( status.dwWaitHint);
if( status.dwCurrentState == SERVICE_RUNNING)
{
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
outfile<<"啟動成功 \n";
return true;
}
}
}
//如果處于暫停狀態,則恢復
if( status.dwCurrentState == SERVICE_PAUSED)
{
outfile<<"服務";
outfile<<ServiceName;
outfile<<"處于停止狀態 \n";
CString str;
str.Format("net continue %s",ServiceName);
WinExec(str,SW_SHOW);
while( ::QueryServiceStatus( hSvc, &status) == TRUE)
{
if( status.dwCurrentState == SERVICE_RUNNING)
{
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
outfile<<"恢復服務成功 \n";
return true;
}
}
}
outfile<<"\n";
outfile.close();
::CloseServiceHandle( hSvc);
::CloseServiceHandle( hSC);
return false;
}
http://blog.csdn.net/suiyuan1767/article/details/6712516