3

I want to check if a win32 EXE file is already running (only knowing the file path and name).

Please tell me how to realize it with win32 API code.

Thanks a lot!

I mean to have each EXE path only running one instance.

3 Answers3

3

Given only a path to the EXE, you will need to enumerate the running processes until you find one with a matching path. Look at EnumProcesses() or Process32First()/Process32Next() for that. See Process Enumeration on MSDN for more details and code examples.

Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
0

By reading Remy Lebeau's answer I succeed to check if the current application is already running in other processes with the following code:

DWORD processes[4096];
DWORD bytesGot;
EnumProcesses(processes, sizeof processes, &bytesGot);
DWORD processesCount = bytesGot / sizeof(DWORD);

WCHAR currName[MAX_PATH];
GetModuleFileNameEx(GetCurrentProcess(), NULL, currName, MAX_PATH);
DWORD currProcessId = GetCurrentProcessId();

for(int x=0;x<=processesCount-1;x++)
{
    HANDLE process = OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, FALSE, processes[x]);
    WCHAR name[MAX_PATH];
    GetModuleFileNameEx(process,NULL, name, MAX_PATH);
    CloseHandle(process);
    if (processes[x]!=currProcessId&& wcscmp(name, currName)==0) return 0;
}

Thanks to Remy Lebeau a lot :) Great useful hints.

  • This sort of code I wrote is to prevent one EXE file from running two or more processes. –  Oct 01 '19 at 05:42
  • 4
    That's the wrong solution to that problem. Use a named murex to do that. Also this code has no error checking. – David Heffernan Oct 01 '19 at 06:15
  • @David Heffernan how is that wrong? –  Oct 01 '19 at 06:24
  • 1
    Well, it's subject to a race. Perfectly possible for two instances of the process to start. The way to solve your problem is to use a named mutex. There are many examples here and in other places. If only you'd asked about your problem rather than your solution. – David Heffernan Oct 01 '19 at 07:00
  • Also trivially defeated by changing the executable file name. – David Heffernan Oct 01 '19 at 07:01
  • Perhaps I didn't make it clear. I mean to have _**each EXE file path**_ running only one instance, not that to have _**this product**_ running only one instance. Therefore, this code solves it well for me. –  Oct 02 '19 at 00:54
  • So the user just creates a copy of the exe file and hey presto, that one program be run run twice. – David Heffernan Oct 02 '19 at 05:26
  • @David Heffernan Yes –  Oct 02 '19 at 05:50
-3

create a blank file on startup and check the file exist.

yumetodo
  • 1,147
  • 7
  • 19
  • 1
    This solution is bad because you have no guarantee that someone will not manually delete the file. If so, you'll consider that the _.exe_ is not running despite it still is. Wasn't me that has downvoted though. – Fareanor Oct 07 '19 at 11:40