Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to capture pid of a linux daemon run from init.d

Tags:

linux

pid

I have started a service daemon , by running the binary(written in C++) through script file stored rc5.d .

But I am not sure how to capture the pid of the daemon process and store it in pid file in /var/run/.pid . So that I can use the pid for termination. How can I do this?

like image 263
Sirish Avatar asked Apr 29 '10 08:04

Sirish


3 Answers

Try using start-stop-daemon(8) with the --pidfile argument in your init script. Have your program write its PID to a specified location (usually determined in a configuration file).

What you have to look out for is stale PID files, for instance, if a lock file persisted across a reboot. That logic is best implemented in the init script itself, hence the --exec option to start-stop-daemon.

E.g, if /var/run/foo.pid is 1234, and /proc/1234/exe isn't your service, the lock file is stale and should be quietly removed, allowing the service to start normally.

As far as your application goes, just make sure the location of the lockfile is configurable, and some means exists to tell the init script where to put it.

For instance: (sample: /etc/default/foo) :

PIDFILE=/var/run/foo.pid
OTHEROPTION=foo

Then in /etc/init.d/foo :

[ -f /etc/default/foo ] && . /etc/default/foo

Again, other than writing to the file consistently, all of this logic should be handled outside of your application.

like image 181
Tim Post Avatar answered Sep 18 '22 03:09

Tim Post


If you know the port the program has open, use fuser command to determine the pid.

like image 32
mindas Avatar answered Sep 20 '22 03:09

mindas


You could go about more than one way:

  1. In your program use getpid to write it to a configurable file (perhaps looking in ENV)
  2. Use $! after starting the program (this doesn't work for me on archlinux though :-?)
  3. After starting the program, use pidof
like image 43
nc3b Avatar answered Sep 18 '22 03:09

nc3b