我正在寻找一种查找特定 Windows 服务的进程 ID 的好方法。
特别是,我需要找到 Windows 附带的默认“WebClient”服务的 pid。它作为 svchost.exe 进程中的“本地服务”托管。我发现当我使用 netstat 来查看哪些进程正在使用哪些端口时,它会在进程名称下列出 [WebClient],所以我希望有一些(相对)简单的机制来查找此信息。
这是一个极简的 C++ 函数,可以完全满足您的需求:
DWORD GetServicePid(const char* serviceName)
{
const auto hScm = OpenSCManager(nullptr, nullptr, NULL);
const auto hSc = OpenService(hScm, serviceName, SERVICE_QUERY_STATUS);
SERVICE_STATUS_PROCESS ssp = {};
DWORD bytesNeeded = 0;
QueryServiceStatusEx(hSc, SC_STATUS_PROCESS_INFO, reinterpret_cast<LPBYTE>(&ssp), sizeof(ssp), &bytesNeeded);
CloseServiceHandle(hSc);
CloseServiceHandle(hScm);
return ssp.dwProcessId;
}
DWORD TForm6::GetServicePid(const wchar_t* serviceName) {
// Open the Service Control Manager
const auto hScm = OpenSCManager(nullptr, nullptr, SC_MANAGER_CONNECT);
if (hScm == NULL) {
std::cerr << "Failed to open the Service Control Manager." << std::endl;
return 0;
}
// Open the service with query status access
const auto hSc = OpenService(hScm, serviceName, SERVICE_QUERY_STATUS);
if (hSc == NULL) {
std::cerr << "Failed to open the service." << std::endl;
CloseServiceHandle(hScm);
return 0;
}
// Query the service status
SERVICE_STATUS_PROCESS ssp = {};
DWORD bytesNeeded = 0;
if (!QueryServiceStatusEx(hSc, SC_STATUS_PROCESS_INFO, reinterpret_cast<LPBYTE>(&ssp), sizeof(ssp), &bytesNeeded)) {
std::cerr << "Failed to query service status." << std::endl;
CloseServiceHandle(hSc);
CloseServiceHandle(hScm);
return 0;
}
// Clean up handles
CloseServiceHandle(hSc);
CloseServiceHandle(hScm);
return ssp.dwProcessId;
}