问题
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