Allow only one copy of the program to run on Linux

I need only one copy of my program on the system. How can I search for other copies in the system from C code? I want something like this

# program & [1] 12586 # program & Program is already running 

The best idea I have is to create .lock files. But I did not find any motive in them.

Thanks.

+4
source share
2 answers

One of the daemons I wrote opened a UNIX domain socket for normal communication with the daemon client. Other instances then checked to see if they could connect to this socket. If they could, another instance is currently working. Edit: As @psmears pointed out, there is a race condition. Other instances should simply try to create the same listening socket. This will fail if it is already in use.

Lock files work more often than this special case. You can create a (empty) file in a well-known place, and then use file locks, say with fcntl(2) and F_SETLK and F_GETLK to lock this file or determine if the lock is locked. May not work on NFS. Locks are cleared when your process dies, so this should work and carry over (at least to HP-UX). Some daemons like to upload pid to this file if they determine that another instance is not running.

+3
source

You can use named sempahores, which is a very standard approach to this problem. Your program calls semctl () to find if there are any active sempahores, then checks to see if you can run it. If you do not find it, you will create a sempahore.

The operating system handles the problem of killing processes with kill -9 and the output of sempahores. You need to read the man page for semctl and sem_open for your machines to find out what this mechanism is.

+1
source

All Articles