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

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


You can use GetExitCodeProcess. It will return STILL_ACTIVE (259) if the process is still running (or if it happened to exit with that exit code :( ).


The process handle will be signaled if it exits.

So the following will work (error handling removed for brevity):

BOOL IsProcessRunning(DWORD pid){    HANDLE process = OpenProcess(SYNCHRONIZE, FALSE, pid);    DWORD ret = WaitForSingleObject(process, 0);    CloseHandle(process);    return ret == WAIT_TIMEOUT;}

Note that process ID's can be recycled - it's better to cache the handle that is returned from the CreateProcess call.

You can also use the threadpool API's (SetThreadpoolWait on Vista+, RegisterWaitForSingleObject on older platforms) to receive a callback when the process exits.

EDIT: I missed the "want to do something to the process" part of the original question. You can use this technique if it is ok to have potentially stale data for some small window or if you want to fail an operation without even attempting it. You will still have to handle the case where the action fails because the process has exited.


#include <cstdio>#include <windows.h>#include <tlhelp32.h>/*!\brief Check if a process is running\param [in] processName Name of process to check if is running\returns \c True if the process is running, or \c False if the process is not running*/bool IsProcessRunning(const wchar_t *processName){    bool exists = false;    PROCESSENTRY32 entry;    entry.dwSize = sizeof(PROCESSENTRY32);    HANDLE snapshot = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, NULL);    if (Process32First(snapshot, &entry))        while (Process32Next(snapshot, &entry))            if (!wcsicmp(entry.szExeFile, processName))                exists = true;    CloseHandle(snapshot);    return exists;}