I know how to use CreateToolhelp32Snapshot or EnumProcesses to enumerate processes but I was trying to experiment with different ways of doing it (I’m still learning and am trying to experiment with different ways of doing things and different ways of approaching problems).
I thought perhaps using for (DWORD i = 0; i < 1000; i++) {OpenProcess(PROCESS_VM_READ, FALSE, i)}
to iterate over the processes and if OpenProcess succeeds I know I have a valid PID. I picked 1000 just for testing purposes to limit the results. Code as follows:
VOID getProcessList() {
LPSTR procName[MAX_PATH];
HANDLE pHandle = NULL;
//try and open a handle to the process ID. Returns NULL if not a valid process ID
for (DWORD i = 0; i < 1000; i++) {
pHandle = OpenProcess(PROCESS_VM_READ | PROCESS_QUERY_INFORMATION, FALSE, i);
//if process ID does not exist try the next one
if (pHandle == NULL) {
continue;
}
//get module name
GetModuleBaseName(pHandle, NULL, procName, MAX_PATH);
//if process exists print it's details
wprintf(L"%s %dn", procName, i);
CloseHandle(pHandle);
}
printf("All processes enumerated");
}
int main() {
printf("Process Name Process IDnn");
getProcessList();
}
It works, but when compared to task manager it does not return all of the processes that are listed on task manager – only the ones that I have started (as opposed to CreateToolhelp32Snapshot which returns everything). I assume it has something to do with permissions and the PROCESS_VM_READ
permission, but I was looking through the other available permissions and couldn’t find anything else to use.
user086340 is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.