简体   繁体   中英

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

如何在给定进程名称的Windows上运行可执行文件,例如program.exe?

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.

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.
}

Assumptions: since you mention '.exe', you want this for some flavor of Windows. You want to write a program in C++ to determine whether a program with a particular executable name is running (regardless of the language used to implement the target program).

Enumerate the running processes using either the Toolhelp API or the process status API. Compare the name of the executable for each running process to the one you're looking for (and be aware that there may be more than one process with that executable name).

hProcessInfo = OpenProcess( PROCESS_ALL_ACCESS, FALSE, pe32.th32ProcessID );

            do{
                if(strcmp(pe32.szExeFile,"process.exe") == 0)
                {
                    processfound = true;
                    break;
                }
}while( Process32Next( hProcessSnap, &pe32 ) );

If you don't want to get process detail from code just press Ctrl+Alt+Del and check process list.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM