tags:

views:

554

answers:

3

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?

+1  A: 

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.

Tim Post
@Tim Post but this option only checks whether to start the daemon or not if it is already running. I want is there any standard way in writing the pid to /var/run/
siri
@Sirish - Just test to see if the file exists, create it if it doesn't, write the PID and close it. If it exists, there's a very good chance that the server is already running. Testing for stale lockfiles is much easier to do in the init script.
Tim Post
@Sirish - Updated my answer, I _think_ its what you want?
Tim Post
A: 

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

mindas
A: 

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
nc3b