How to find out if .exe works in C ++?

How can you find out if an executable file is running on Windows with a process name, for example. program.exe?

+3
source share
4 answers

The standard C ++ library does not support such support. To do this, you need the operating system API. If it is Windows, you should use CreateToolhelp32Snapshot (), then Process32First and Process32Next to repeat running processes. Beware of the inevitable state of the race, the process could have come to the point when you found it.

+5
source

I just created one using the suggestion of Hans. Works like a champion!

Oh, here is the main code.

, CStrings sAppPath sAppName.

StartProcess - , CreateProcess PID ( ). .

, , , . - c:\windows\ notepad.exe 10 .

#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.
}
+2

: ".exe", Windows. ++, , ( , ).

List running processes using the API Toolkey or the process status API. Compare the name of the executable for each running process with the one you are looking for (and remember that there can be more than one process with this executable name).

0
source
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 do not want to get process details from the code, just press Ctrl + Alt + Del and check the list of processes.

0
source

Source: https://habr.com/ru/post/1756997/


All Articles