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

白昼怎懂夜的黑 提交于 2019-12-19 10:24:10

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/1774129/how-can-we-find-the-process-id-of-a-running-windows-service

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!