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);


}
发布了90 篇原创文章 · 获赞 33 · 访问量 21万+

猜你喜欢

转载自blog.csdn.net/y281252548/article/details/90240889
今日推荐