How do I find out if a .exe is running in c++?

10,817

Solution 1

The C++ standard library has no such support. You need an operating system API to do this. If this is Windows then you'd use CreateToolhelp32Snapshot(), followed by Process32First and Process32Next to iterate the running processes. Beware of the inevitable race condition, the process could have exited by the time you found it.

Solution 2

I just created one using Hans suggestion. Works like a champ!

Oh and here is the basic code.

Please you will have to add CStrings sAppPath and sAppName.

StartProcess is a small function that uses CreateProcess and returns the PID(not used here). You will need to replace it.

This is not a complete program, just the code to find if the program is running using Hans suggestion. A fun test is to set the path to c:\windows\ and the app to notepad.exe and set it for 10 seconds.

#include <tlhelp32.h>
PROCESSENTRY32 pe32 = {0}; 
HANDLE    hSnap;
int       iDone;
int       iTime = 60;
bool      bProcessFound;

while(true)    // go forever
{
    hSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS,0);
    pe32.dwSize = sizeof(PROCESSENTRY32); 
    Process32First(hSnap,&pe32);     // Can throw away, never an actual app

    bProcessFound = false;   //init values
    iDone = 1;

    while(iDone)    // go until out of Processes
    {
        iDone = Process32Next(hSnap,&pe32);
        if (strcmp(pe32.szExeFile,sAppName) == 0)    // Did we find our process?
        {
            bProcessFound = true;
            iDone = 0;
        }
    }

    if(!bProcessFound)    // if we didn't find it running...
    {
        startProcess(sAppPath+sAppName,"");             // start it
    }
    Sleep(iTime*1000);    // delay x amount of seconds.
}
Share:
10,817
blood
Author by

blood

Updated on June 07, 2022

Comments

  • blood
    blood almost 2 years

    How can you find out if an executable is running on Windows given the process name, e.g. program.exe?