天天看點

Windows 服務程式 監控 服務程式 停止則 重新啟動服務

 用64位服務程式 調用cmd 啟動服務失敗,後編譯32位服務程式,用下面的函數 啟動成功

BOOL fstartservice(string vname){
	  // 打開服務管理對象
	 SC_HANDLE hSC = OpenSCManager( NULL,
	 NULL, GENERIC_EXECUTE);
	 if( hSC == NULL)
	 {
	printf("OpenScManager error:%d\n",GetLastError());
	 return false;
	 }
	 // 打開列印服務。
	 SC_HANDLE hSvc = OpenService( hSC, vname.c_str(),
	 SERVICE_START | SERVICE_QUERY_STATUS | SERVICE_STOP);
	 if( hSvc == NULL)
	 {
	printf("OpenService error:%d\n",GetLastError());
	CloseServiceHandle( hSC);
	return false;
	 }
	 // 獲得服務的狀态
	 SERVICE_STATUS status;
	 if( QueryServiceStatus( hSvc, &status) == FALSE)
	 {
	printf("QueryServiceStatus error:%d\n",GetLastError());
	CloseServiceHandle( hSvc);
	CloseServiceHandle( hSC);
	return false;
	 }
	 //如果處于停止狀态則啟動服務,否則停止服務。
	 if( status.dwCurrentState == SERVICE_RUNNING)
	 {
//	// 停止服務
//	if( ControlService( hSvc,
//	SERVICE_CONTROL_STOP, &status) == FALSE)
//	{
//	printf("ControlService Stop error:%d\n",GetLastError());
//	CloseServiceHandle( hSvc);
//	CloseServiceHandle( hSC);
//	return;
//	}
//	// 等待服務停止
//	while( QueryServiceStatus( hSvc, &status) == TRUE)
//	{
//	Sleep( status.dwWaitHint);
//	if( status.dwCurrentState == SERVICE_STOPPED)
//	{
//	printf("QueryServiceStatus stop success.\n");
//	CloseServiceHandle( hSvc);
//	CloseServiceHandle( hSC);
//	return;
	   return true;
//	}
//	}
	 }else if( status.dwCurrentState == SERVICE_STOPPED){
	// 啟動服務
	if( StartService( hSvc, NULL, NULL) == FALSE)
	{
	printf("start service error:%d\n",GetLastError());
	CloseServiceHandle( hSvc);
	CloseServiceHandle( hSC);
	return false;
	}
	// 等待服務啟動
	while( QueryServiceStatus( hSvc, &status) == TRUE)
	{
	Sleep( status.dwWaitHint);
	if( status.dwCurrentState == SERVICE_RUNNING)
	{
	printf("start success.\n");
	CloseServiceHandle( hSvc);
	CloseServiceHandle( hSC);
	return true;
	}
	}
	 }
	printf("Start error:%d\n",GetLastError());
	CloseServiceHandle( hSvc);
	CloseServiceHandle( hSC);


}