I’ll preface this post with the fact that it will be fairly technical. I have been trying to write a Windows program which can get the EXE path of a specified process ID (PID). I found a couple different ways, so thought I would go through them here.

This Rhino is curious to find EXE paths of applications

So, while going through this process, I found 2 different ways of doing this, both from the Internet and combing through MSDN documentation. If you just want to get the full EXE path of a certain PID, turns out it is very simple. If you want to get a full PROCESSENTRY32 structure however, it’s a little more challenging.

First, the easier solution of just getting the full EXE path. Turns out there is a lovely system call called QueryFullProcessImageName┬áthat does exactly what I wanted. (Of course, I only found this after hours of searching and doing the other way, but that is besides the point.) It’s almost comical how easy it is to use:

DWORD PID = 1337; // something here

char buffer[MAX_PATH];
QueryFullProcessImageName(hProcess, 0, buffer, &value);
printf("EXE Path: %s\n", buffer);

Simple, right?

The only downside to this method is that you only get the full EXE path, nothing else. For more information, you might want to fill a PROCESSENTRY32 structure, which can be done in a few steps:

  1. Create a snapshot of all processes with CreateToolhelp32Snapshot()
  2. Iterate through all processes with Process32First() and Process32Next()

A source example of this would look like:

DWORD PID = 1337; // something here

HANDLE hSnapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, PID);
    peInfo.dwSize = sizeof(peInfo); // this line is REQUIRED
    BOOL nextProcess = Process32First(hSnapshot, &peInfo);
    bool found = false;
	if(peInfo.th32ProcessID == PID)
	    found = true;
	nextProcess= Process32Next(hSnapshot, &peInfo);

What is happening in this code sample is that a snapshot is being taken of the current processes in the system. If the iterated process has the desired PID, the process is examined. Information about a process is stored in the PROCESSENTRY32 structure. There are a lot of interesting pieces of information in that structure, but we are only concerned with the szExeFile field, which is the EXE name of the application. Note that it is only the application, not the full path, such as ‘itunes.exe’, not ‘C:\Program Files\iTunes\iTunes.exe’. If you want the full path, use the first solution presented above.

« »