Shared publicly  - 
 
I'm migrating the oldest Linux server still on our network. One of the shell scripts on it runs in a loop, sleeping for 15 seconds then scanning some files and acting on them.

In order to "daemonize" it a bit more "properly" than the way it's written now, I need to make it fork at the beginning and exit, leaving behind a child which prints its PID into /var/run/programm.pid and keeps running in a loop.

Here is a little bash code sample which demonstrates how I did this:

#!/bin/bash

# append all output of this script to that file
exec >> ttt.out
echo $$: started running

# Decide whether we are already the child or not
if [[ "$IS_DAEMON" != "yes" ]]
then
echo $$: going to daemonize
# pass a flag to the child that it is a child and re-execute ourselve in the background
env IS_DAEMON=yes $0 $* &
# parent exits
exit 0
fi

# This is the child
echo $$: is daemon
# Do interesting stuff (like, sleep for a year :)
sleep 365d
exit 0

The only dependency on bash(1) vs. standard shell here is the use of built-in "[[", "]]" instead of external test (aliased "[").

With this in place, I can continue treat this program just like any other daemon invoked through RHEL/CentOS/Fedora "daemon" init.d functions.
1
Add a comment...