DrBeco
DrBeco

Reputation: 11785

How to determine if the application is already running? C portable Linux/Win

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

Upvotes: 2

Views: 3276

Answers (4)

bdonlan
bdonlan

Reputation: 231373

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

Upvotes: 3

Charlie Martin
Charlie Martin

Reputation: 112404

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.

Upvotes: 1

Dhaivat Pandya
Dhaivat Pandya

Reputation: 6536

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.

Upvotes: 0

Keith Nicholas
Keith Nicholas

Reputation: 44316

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.

Upvotes: 2

Related Questions