windows查询服务状态C++

本文介绍了如何在Windows 7及更高版本中使用C++代码查询服务的状态,由于服务和进程在不同session运行,该方法提供了获取服务状态的解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前面blog说过windows(7及以后)中,服务和进程位于不同的session,如何查询服务状态,这里贴出代码

	TCHAR szSvcName[] = TEXT("SSIT_Client_Service");
	SC_HANDLE schSCManager;
	SC_HANDLE schService;

	SERVICE_STATUS_PROCESS ssStatus;
	DWORD dwOldCheckPoint;
	DWORD dwStartTickCount;
	DWORD dwWaitTime;
	DWORD dwBytesNeeded;

	// Get a handle to the SCM database. 

	schSCManager = OpenSCManager(
		NULL,                    // local computer
		NULL,                    // ServicesActive database 
		SC_MANAGER_ALL_ACCESS);  // full access rights 

	if (NULL == schSCManager)
	{
		printf("OpenSCManager failed (%d)\n", GetLastError());

	}

	// Get a handle to the service.

	schService = OpenService(
		schSCManager,         // SCM database 
		szSvcName,            // name of service         
		SERVICE_QUERY_STATUS |
		SERVICE_ENUMERATE_DEPENDENTS
		);  // full access 

	if (schService == NULL)
	{
		CloseServiceHandle(schSCManager);
	}
	else
	{
		// Check the status in case the service is not stopped. 

		if (!QueryServiceStatusEx(
			schService,                     // handle to service 
			SC_STATUS_PROCESS_INFO,         // information level
			(LPBYTE)&ssStatus,             // address of structure
			sizeof(SERVICE_STATUS_PROCESS), // size of structure
			&dwBytesNeeded))              // size needed if buffer is too small
		{
			printf("QueryServiceStatusEx failed (%d)\n", GetLastError());
		}
		else
		{
			// Check if the service is already running. It would be possible 
			// to stop the service here, but for simplicity this example just returns. 
			switch (ssStatus.dwCurrentState)
			{
			case SERVICE_STOPPED:
			case SERVICE_STOP_PENDING:
                break;
			case SERVICE_PAUSED:
			case SERVICE_PAUSE_PENDING:
				break;
			case SERVICE_CONTINUE_PENDING:
			case SERVICE_RUNNING:
			case SERVICE_START_PENDING:
				break;
			}
		}
	}

	CloseServiceHandle(schService);
	CloseServiceHandle(schSCManager);

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值