Hi everyone,
In exploring the workings of the process API, I am attempting to write a simple program that would display the PIDs and filepaths of every running process on my computer.
This is done by calling the QueryFullProcessImageName function, however, it fails every time even though it seems as though I have given it the appropriate security permissions in the handle, etc.
#include <Windows.h>
#include <iostream>
#include <Psapi.h>
usingnamespace std;
void printProcPath(DWORD pid) {
HANDLE hProc = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION | PROCESS_QUERY_INFORMATION, false, pid);//create process handle
if (hProc = NULL) cout << "Cannot open process."; // if cannot open process, return error description
LPWSTR path = new WCHAR[MAX_PATH];//will hold .exe path to be returned
DWORD charsCarried = MAX_PATH; // holds size of path[], will then hold amount of characters returned by QueryFullProcessImageName
BOOL iResult = QueryFullProcessImageName(hProc, 0, path, &charsCarried);
if (iResult == 0) { //if QueryFullProcessImageName fails, return description
cout << "Cannot get process path.";
}
else { //if success, print path
wcout << path;
}
}
int main() {
DWORD PIDs[1024], bytesReturned, procQty;
EnumProcesses(PIDs, sizeof(PIDs), &bytesReturned);//gets PIDs and stores it into array
procQty = bytesReturned / sizeof(DWORD);
for (DWORD i = 0; i < procQty; ++i) { // for each PID, print result in format <PID>: {<process_name> | <error_description>}
cout << PIDs[i] << ": ";
printProcPath(PIDs[i]);
cout << '\n';
}
cin.get();//wait for enter press before exiting
return 0;
}
Upon running, in my console window I get:
0: Cannot get process path.
4: Cannot get process path.
344: Cannot get process path.
...and so on until all PIDs have been enumerated.
Am I doing something wrong, not meeting some prerequisite, etc?
Any assistance would be appreciated.
Thank you.
Line 12 has an assignment operator in the IF(). This is effectively destroying any good returned handle from OpenProcess().
Beginners should get used to do comparisons backwards: First the value, then the variable. This way if they forget the second Equals sign the compiler will complain:
if (NULL == hProc) //2 Equals signs, not just one.