我使用下面的代码以及进程名称获取了正在运行的服务的进程ID,但我真正想要的是服务名称/密钥。有没有办法从进程ID或者进程名称?使用c ++
DWORD aProcesses[1024], cbNeeded, cProcesses;
unsigned int i;
if ( !EnumProcesses( aProcesses, sizeof(aProcesses), &cbNeeded ) )
{
return 1;
}
// Calculate how many process identifiers were returned.
cProcesses = cbNeeded / sizeof(DWORD);
// Print the name and process identifier for each process.
for ( i = 0; i < cProcesses; i++ )
{
if( aProcesses[i] != 0 )
{
PrintProcessNameAndID( aProcesses[i] );
}
}
和..
void tt_coreutils_ns::PrintProcessNameAndID( DWORD processID )
{
TCHAR szProcessName[MAX_PATH] = TEXT("<unknown>");
// Get a handle to the process.
HANDLE hProcess = OpenProcess( PROCESS_QUERY_INFORMATION |
PROCESS_VM_READ,
FALSE, processID );
// Get the process name.
if (NULL != hProcess )
{
HMODULE hMod;
DWORD cbNeeded;
if ( EnumProcessModules( hProcess, &hMod, sizeof(hMod),
&cbNeeded) )
{
GetModuleBaseName( hProcess, hMod, szProcessName,
sizeof(szProcessName)/sizeof(TCHAR) );
}
}
// Print the process name and identifier.
_tprintf( TEXT("%s (PID: %u)\n"), szProcessName, processID );
// Release the handle to the process.
CloseHandle( hProcess );
}
更新代码
DWORD pId=GetCurrentProcessId();
SC_HANDLE hSCM = NULL;
PUCHAR pBuf = NULL;
ULONG dwBufSize = 0x00;
ULONG dwBufNeed = 0x00;
ULONG dwNumberOfService = 0x00;
LPENUM_SERVICE_STATUS_PROCESS pInfo = NULL;
hSCM = OpenSCManager(NULL, NULL, SC_MANAGER_ENUMERATE_SERVICE | SC_MANAGER_CONNECT);
if (hSCM == NULL)
{
printf_s("OpenSCManager fail \n");
return 0xffff0001;
}
EnumServicesStatusEx(
hSCM,
SC_ENUM_PROCESS_INFO,
SERVICE_WIN32, // SERVICE_DRIVER
SERVICE_STATE_ALL,
NULL,
dwBufSize,
&dwBufNeed,
&dwNumberOfService,
NULL,
NULL);
if (dwBufNeed < 0x01)
{
printf_s("EnumServicesStatusEx fail ?? \n");
return 0xffff0002;
}
dwBufSize = dwBufNeed + 0x10;
pBuf = (PUCHAR) malloc(dwBufSize);
EnumServicesStatusEx(
hSCM,
SC_ENUM_PROCESS_INFO,
SERVICE_WIN32, // SERVICE_DRIVER,
SERVICE_ACTIVE, //SERVICE_STATE_ALL,
pBuf,
dwBufSize,
&dwBufNeed,
&dwNumberOfService,
NULL,
NULL);
pInfo = (LPENUM_SERVICE_STATUS_PROCESS)pBuf;
for (ULONG i=0;i<dwNumberOfService;i++)
{
cout<<"display name "<<pInfo[i].lpDisplayName<<"\t service name: ";
cout<< pInfo[i].lpServiceName<<"\tid: "<<pInfo[i].ServiceStatusProcess.dwProcessId<<endl<<endl;
if(pId==pInfo[i].ServiceStatusProcess.dwProcessId)
{
cout<<pInfo->lpServiceName;
}
}
答案 0 :(得分:2)
使用EnumServicesStatusEx枚举所有服务(将SERVICE_WIN32
作为服务类型传递)。在输出中,您将获得包含服务名称的ENUM_SERVICE_STATUS_PROCESS
结构和具有SERVICE_STATUS_PROCESS
字段的另一个DWORD dwProcessId
结构。
这样您就可以将进程ID映射到服务名称/密钥。