根据服务名查询该服务是否运行 用c++编码实现windows和Linux平台
时间: 2024-01-21 08:19:09 浏览: 32
在 Windows 平台上,可以使用以下代码来检查服务是否正在运行:
```cpp
#include <Windows.h>
bool IsServiceRunning(const char* serviceName)
{
SC_HANDLE scmHandle = OpenSCManager(NULL, NULL, SC_MANAGER_CONNECT);
if (scmHandle == NULL)
{
return false;
}
SC_HANDLE serviceHandle = OpenService(scmHandle, serviceName, SERVICE_QUERY_STATUS);
if (serviceHandle == NULL)
{
CloseServiceHandle(scmHandle);
return false;
}
SERVICE_STATUS serviceStatus;
if (!QueryServiceStatus(serviceHandle, &serviceStatus))
{
CloseServiceHandle(serviceHandle);
CloseServiceHandle(scmHandle);
return false;
}
CloseServiceHandle(serviceHandle);
CloseServiceHandle(scmHandle);
return serviceStatus.dwCurrentState == SERVICE_RUNNING;
}
```
在 Linux 平台上,可以使用以下代码来检查服务是否正在运行:
```cpp
#include <systemd/sd-daemon.h>
bool IsServiceRunning(const char* serviceName)
{
return sd_booted() > 0 && sd_is_systemd() > 0 && sd_is_unit_active(serviceName, 0) > 0;
}
```
需要注意的是,Linux 平台上需要链接 `libsystemd` 库。在编译时需要加上 `-lsystemd` 参数。