I got the process id of the running service using the code below as well as the process name, but i all i really want is the service name/key.Is there a way to get that from either the process id or the process name? Using 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] );
}
}
and..
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 );
}
updated code
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;
}
}
Enumerate all the services using EnumServicesStatusEx (pass
SERVICE_WIN32as a service type). In the output, you’ll getENUM_SERVICE_STATUS_PROCESSstructs that contain service name and anotherSERVICE_STATUS_PROCESSstruct, which hasDWORD dwProcessIdfield.This way you can map process id to a service name/key.