Daemon process

I wish to make a process run in the background, but only one instance of it, and not many,
so when the program is loaded, it has to check whether another instance of the same
program is running and if so to exit. How do I do this ?

If your system supports the semget() and semop() calls that are included in one of the optional features in the POSIX standards, you can use semget() to get access to a semaphore with a key that is known to your daemon. After getting the semaphore ID you can use semop() with an array of two operations at the start of your program. These operations are:

sem_num   sem_op   sem_flg
=======   ======   =======
   0         0     IPC_NOWAIT
   0         1     SEM_UNDO

If the semop() call fails with EAGAIN, another daemon is already running and owns the semaphore. If the semop() call succeeds, this daemon owns the semaphore until it terminates. (It doesn't matter if this daemon terminates due to receipt of an uncaught signal or terminates normally by calling exit, the SEM_UNDO flag will release ownership of the semaphore when the daemon terminates.)

If you don't have access to a similar set of semaphore operations, a common approach is to atomically create (with open flags O_CREAT | O_EXCL ) a lock file and write the PID of the daemon that created the lock into the lock file. The daemon should then remove the lock file before it exits. (If the daemon is killed before it can remove the lock file, another daemon won't be able to start until you manually remove the lock file.)

1 Like

Hi Sundaresh,
I am not sure exactly if this helps...but let me give an idea...
I assume you have a script which you wanted to run on background, only one instance of it.

# inside the script, you will add these few lines to check if the script is already running

COUNT=`ps -ef SCRIPT_NAME | wc -l`
if [ "$COUNT" -eq 0 ]
then
  # run the script
 /full/path/SCRIPT_NAME &
else
  echo "Already an instance of the script is running"
fi
exit 0

A correction

COUNT=`ps -ef | grep -wc 'CRIPT_NAME'`

or

COUNT=`pgrep 'SCRIPT_NAME'
| wc -l`

A comment for Don's pidfile proposal:
a standard pathname is /var/run/SCRIPT_NAME.pid

Thanks Don, my daemon does use shared memory, but the semaphore seems to be the right way.
I did'nt think of it.