枚举系统服务
#include <stdio.h>
#include <windows.h>
// win32应用程序
#define WIN_32_PROCESS (SERVICE_WIN32_OWN_PROCESS)
int main() {
// 获取系统服务列表
SC_HANDLE scHandle = OpenSCManager(NULL, NULL, SC_MANAGER_ALL_ACCESS);
if (scHandle == NULL) {
DWORD errorCode = GetLastError();
printf("打开系统服务管理错误码:%lu \r\n", errorCode);
switch (errorCode) {
case ERROR_ACCESS_DENIED:
printf("打开系统服务管理错误:%s \n", "权限限制");
break;
case ERROR_DATABASE_DOES_NOT_EXIST:
printf("打开系统服务管理错误:%s \n", "数据不存在");
break;
default:
printf("打开系统服务管理错误:%s \n", "未知错误");
}
return 0;
}
DWORD dwBuffSize = sizeof(ENUM_SERVICE_STATUS) * 512;
// 枚举win32应用程序
DWORD dwServiceType = WIN_32_PROCESS;
DWORD dwByteNeeded, dwServicesReturned, lpResumeHandle = 0;
ENUM_SERVICE_STATUS enumServiceStatus[512] = {0};
BOOL ret = EnumServicesStatus(scHandle,
dwServiceType,
SERVICE_STATE_ALL,
enumServiceStatus,
dwBuffSize,
&dwByteNeeded,
&dwServicesReturned,
&lpResumeHandle
);
if (ret == FALSE) {
printf("枚举系统服务错误\n");
return 0;
}
for (int i = 0; i < dwServicesReturned; ++i) {
char desc[100] = {0};
wsprintf(desc, "服务名:%s 展示状态:%s %lu", enumServiceStatus[i].lpServiceName, enumServiceStatus[i].lpDisplayName,enumServiceStatus[i].ServiceStatus.dwCurrentState);
switch (enumServiceStatus[i].ServiceStatus.dwCurrentState) {
case SERVICE_PAUSED:
strcat(desc, " 暂停");
break;
case SERVICE_STOPPED:
strcat(desc, " 停止");
break;
case SERVICE_RUNNING:
strcat(desc, " 运行");
break;
default:
strcat(desc, " 其他");
break;
}
printf("%s\n", desc);
}
}
输出
服务名:WdiServiceHost 展示状态:Diagnostic Service Host 4 运行
服务名:WdiSystemHost 展示状态:Diagnostic System Host 4 运行
服务名:WdNisSvc 展示状态:Microsoft Defender Antivirus Network Inspection Service 1 停止
服务名:WerSvc 展示状态:Windows Error Reporting Service 1 停止
服务名:WinDefend 展示状态:Microsoft Defender Antivirus Service 1 停止
服务名:WinHttpAutoProxySvc 展示状态:WinHTTP Web Proxy Auto-Discovery Service 4 运行
服务名:Winmgmt 展示状态:Windows Management Instrumentation 4 运行