1

我使用下面的代码以及进程名称获得了正在运行的服务的进程 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;
    }
}
4

1 回答 1

2

使用EnumServicesStatusEx枚举所有服务(SERVICE_WIN32作为服务类型传递)。在输出中,您将获得ENUM_SERVICE_STATUS_PROCESS包含服务名称的SERVICE_STATUS_PROCESS结构和另一个具有DWORD dwProcessId字段的结构。

通过这种方式,您可以将进程 ID 映射到服务名称/键。

于 2012-07-16T15:23:51.213 回答