I have started a service daemon , by running the binary(written in C开发者_如何学Python++) 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?
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.
If you know the port the program has open, use fuser
command to determine the pid.
You could go about more than one way:
- In your program use getpid to write it to a configurable file (perhaps looking in ENV)
- Use $! after starting the program (this doesn't work for me on archlinux though :-?)
- After starting the program, use pidof
精彩评论