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.