3

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?

Community
  • 1
  • 1
Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177

1 Answers1

2

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.

Trevor Boyd Smith
  • 18,164
  • 32
  • 127
  • 177
  • Is this not obvious, did it really need a Q&A? – 123 Jun 29 '16 at 14:59
  • 1
    @123 Taking a peek at your profile it looks like you are very experienced with bash and so maybe this is obvious. But for me this is definitely not obvious. The first time I used this function I used it wrong myself and so I don't want others to have the same issue. (additionally there is almost nonexistant documentation and the information you do find on google or stackoverflow usually talks about a different `daemon` and so the naive googler may conflate that information with this specific `daemon` from Redhat /etc/rc.d/init.d/functions.) – Trevor Boyd Smith Jun 29 '16 at 15:16
  • Eh, fair enough :) – 123 Jun 30 '16 at 07:07