开发者

How can we find the process ID of a running Windows Service?

I'm looking for a good way to find the process ID of a particular Windows Service.

In particular, I need to find the pid of the default "WebClient" service that ships with Windows. It's hosted as a "local service" within a svchost.exe process. I see that when I use netstat to see开发者_运维百科 what processes are using what ports it lists [WebClient] under the process name, so I'm hoping that there is some (relatively) simple mechanism to find this information.


QueryServiceStatusEx returns a SERVICE_STATUS_PROCESS, which contains the process identifier for the process under which the service is running.

You can use OpenService to obtain a handle to a service from its name.


Here's a minimalist C++ function to do exactly what you want:

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;
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜