Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When using RHEL's `daemon` init.d function, how do you capture the PID?

This is a followup to RedHat daemon function usage. In the accepted solution the author states "$! is not usable when using [the function] daemon [sourced from /etc/rc.d/init.d/functions]". So my followup question is about getting the PID.

If you want to use the function daemon sourced from /etc/rc.d/init.d/functions, how do you capture the PID?

like image 219
Trevor Boyd Smith Avatar asked Jul 23 '26 16:07

Trevor Boyd Smith


1 Answers

You need to create a wrapper shell script that backgrounds your program and captures the PID using $! and then pass the wrapper shell script to the daemon function.

There may be more elegant ways to daemonize a program without using the function daemon sourced from /etc/rc.d/init.d/functions but this question/answer is specific about using this daemon function. [2]


Here's the low level step by step of why:

I shall use sleep[1] as a standin for any program that you wish to daemonize using the function daemon sourced from /etc/rc.d/init.d/functions.

You are required to create a wrapper shell script that backgrounds sleep and gets the PID via $!. So for example your sleep_wrapper.sh would be:

#!/bin/bash
sleep 100 &
PID=$!
echo $PID

Then you pass this wrapper to daemon via:

daemon sleep_wrapper.sh

If you naively try to call daemon sleep 100 followed by PID=$! you won't get the PID of the process sleep but instead:

  • you will get the PID for runuser
  • runuser which spawns bash process
  • finally bash spawns sleep

[1] Most binary applications don't background themselves and so sleep is a good standin for this example. Obviously to adapt this to your situation you would replace sleep with whatever program you wanted to use.

[2] Seems like there should be better ways to daemonize that do not involve using this specific daemon function.

like image 159
Trevor Boyd Smith Avatar answered Jul 28 '26 16:07

Trevor Boyd Smith



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!