C++, How to determine if a Windows Process is running?

Viewed 146533

This is concerning Windows XP processes.

I have a process running, let's call it Process1. Process1 creates a new process, Process2, and saves its id.

Now, at some point Process1 wants Process2 to do something, so it first needs to make sure that Process2 is still alive and that the user has not not killed it.

How can I check that this process is still running? Since I created it, I have the Process ID, I would think there is some library function along the lines of IsProcessIDValid( id ) but I can't find it on MSDN

13 Answers

The solution provided by @user152949, as it was noted in commentaries, skips the first process and doesn't break when "exists" is set to true. Let me provide a fixed version:

#include <windows.h>
#include <tlhelp32.h>
#include <tchar.h>

bool IsProcessRunning(const TCHAR* const executableName) {
    PROCESSENTRY32 entry;
    entry.dwSize = sizeof(PROCESSENTRY32);

    const auto snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);

    if (!Process32First(snapshot, &entry)) {
        CloseHandle(snapshot);
        return false;
    }

    do {
        if (!_tcsicmp(entry.szExeFile, executableName)) {
            CloseHandle(snapshot);
            return true;
        }
    } while (Process32Next(snapshot, &entry));

    CloseHandle(snapshot);
    return false;
}
char tmp[200] = "taskkill /f /im chrome.exe && \"C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe\"

while (1)
{
    FILE* f;
    f = _popen("tasklist", "r");

    char b[512];
    bzero(b, 512);

    while (fgets(b, 512, f) != NULL)
    {
        if (strncmp(b, "chrome.exe", 8) == 0)
        {
            printf("Chrome running!\n");
            system(tmp);
        }
        else
        {
            printf("Chrome NOT running!\n");
        }
    }
    Sleep(1000);
}
Related