开发者

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

开发者 https://www.devze.com 2022-12-28 09:00 出处:网络
I have started a service daemon, by running the binary(written in C开发者_如何学Python++) through script file stored rc5.d .

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:

  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
0

精彩评论

暂无评论...
验证码 换一张
取 消