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.

Share:
10,141
Error1f1f
Author by

Error1f1f

VB.NET,C/C++,PHP,MySQL programmer.

Updated on June 04, 2022

Comments

  • Error1f1f
    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 using flock()?

  • Flexo
    Flexo about 13 years
    That looked really interesting, but it seems like it's heavily tied to GNOME unless I missed something?
  • dogbane
    dogbane about 13 years
    $! will give you the process id. You don't need to grep ps.
  • E. Verda
    E. Verda about 13 years
    It 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
    William Pursell about 13 years
    This fails, and is a classic race condition. There is no guarantee that only one instance of COMMAND will be running.
  • Jeff Busby
    Jeff Busby about 13 years
    Admittedly 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
    Matt Joiner about 13 years
    I think you mean bind a socket.
  • Pihhan
    Pihhan almost 11 years
    Would not it restrict it to whole system as single instance? Ie. 2 different users cannot have their own instance on single system then?