Writing PID File on Linux
10,141
Solution 1
Just lock the executable file itself.
Solution 2
Wrap the start-up and shut-down with start-stop-daemon.
Solution 3
I use something like this in a couple of initd scripts I've written. Replace the COMMAND with whatever you need
PIDFILE=/var/run/service.pid
COMMAND="java -jar start.jar"
$COMMAND > /dev/null 2>&1 &
echo $! > $PIDFILE
Edited with @dogane 's suggestion, tested as well.
Solution 4
Just use libunique. It is the simplest way.
Comments
-
Error1f1f almost 2 years
I am currently working on a linux daemon that needs to be single instance (i.e restricted to 1 user 1 process). What would be the best way of doing so without having to use
getpid()
to manually write the pid out to /var/run/ and then lock it usingflock()
? -
Flexo about 13 yearsThat looked really interesting, but it seems like it's heavily tied to GNOME unless I missed something?
-
dogbane about 13 years$! will give you the process id. You don't need to grep ps.
-
E. Verda about 13 yearsIt depends on GTK, not Gnome. It is difficult to find Linux desktop without GTK. However, if you are going to use your daemon on a headless server, libunique isn't the best choice.
-
William Pursell about 13 yearsThis fails, and is a classic race condition. There is no guarantee that only one instance of COMMAND will be running.
-
Jeff Busby about 13 yearsAdmittedly this is only a partial answer to his question, it shows how to write the pid file. I use this as a start up script which is used along side a init script which actually checks if the process is already running. I'll post that code tonight when I have time if @Error1f1f hasn't already moved on.
-
Matt Joiner about 13 yearsI think you mean bind a socket.
-
Pihhan almost 11 yearsWould not it restrict it to whole system as single instance? Ie. 2 different users cannot have their own instance on single system then?