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
HANDLE hProcess = OpenProcess(PROCESS_QUERY_INFORMATION, false, PID);

DWORD value = MAX_PATH;
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);
if(hSnapshot)
{
    peInfo.dwSize = sizeof(peInfo); // this line is REQUIRED
    BOOL nextProcess = Process32First(hSnapshot, &peInfo);
    bool found = false;
    while(nextProcess)
    {
	if(peInfo.th32ProcessID == PID)
	{
	    found = true;
	    break;
	}
	nextProcess= Process32Next(hSnapshot, &peInfo);
    }
    if(found)
    {
        printf("%s",peInfo.szExeFile);
    }
    CloseHandle(hSnapshot);
}

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.

« »