2

Is there a way to write a C code that allow us to determine if a previous instance of an application is already running? I need to check this in a portable way for Linux and Windows, both using the last version of GCC avaiable.

Any examples of portable code would be of enormous help. I see two options now:

  1. Check process list. Here linux has good tools, but I don't think the same functions apply to windows. Maybe some gnu libraries for both SO? What libraries, or functions?
  2. Save and lock a file. Now, how to do that in a way that both systems can understand? One problem is where to save the file? Path trees are different from each systems. Also, if a relative path is chosen, two applications can still run with different locked files in different directories.

Thanks! Beco.

PS. The SO have different requisites, so if you know one and not another, please answer. After all, if there is no portable "single" way, I still may be able to use #ifdef and the codes proposed as answer.

C language (not c++), console application, gcc, linux and windows

dsolimano
  • 8,870
  • 3
  • 48
  • 63
DrBeco
  • 11,237
  • 9
  • 59
  • 76

4 Answers4

3

Unfortunately, if you limit yourself to C, you may have difficulty doing this portably. With C++, there's boost interprocess's named_mutex, but on C, you will have to either:

  • UNIXes (including Mac OS): Open and flock a file somewhere. Traditionally you will also write your current PID into this file. NOTE: This may not be safe on NFS; but your options are extremely limited there anyway. On Linux you can use a /dev/shm path if you want to ensure it's local and safe to lock.
  • Windows: Open and lock a named mutex
bdonlan
  • 224,562
  • 31
  • 268
  • 324
2

for windows, a mutex works well.

http://msdn.microsoft.com/en-us/library/ms682411(v=vs.85).aspx

the article also mentions an alternative to a mutex....

To limit your application to one instance per user, create a locked file in the user's profile directory.

Keith Nicholas
  • 43,549
  • 15
  • 93
  • 156
  • Hi @Keith. What is the full path of that directory? Is there a variable that works? I edited the question, to explain some of the doubts when trying to do this in both systems. Thanks for your time! – DrBeco Apr 13 '11 at 06:39
1

The sort of canonical method in Unixland is to have the process write its own PID to a file in a known location. If this file exists, then the program can check its own pid (available by system call) with the one in that file, and if it's unfamiliar you know that another process is running.

Charlie Martin
  • 110,348
  • 25
  • 193
  • 263
0

C does not give in-built facilities to check if an application is already running, so, making it cross platform is difficult/impossible. However, on Linux, one can use IPC. And, on Windows (I'm not very experienced in this category), you may find this helpful.

Dhaivat Pandya
  • 6,499
  • 4
  • 29
  • 43