Writing PID File on Linux
I am currently working o开发者_开发问答n 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 using flock()
?
Wrap the start-up and shut-down with start-stop-daemon.
Just lock the executable file itself.
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.
Just use libunique. It is the simplest way.
If you really can't have a lock file, use a socket instead. Another instance won't be able to start up because the address will already be in use.
精彩评论