As Close to A Real Daemon As Bash Scripts Get

I’ve written a little something which is gaining some traction internally, and I always intended to share it with the world. So… Here. daemon-functions.sh

What it does is allow you to write a bash function called “payload” like so:

function payload() {
while [ true ]; do
checkforterm
date
sleep 1
done
}
source path/to/daemon-functions.sh

Once you’ve done that it all just happens.  daemon-functions gives you logging of stderr, stdout, a pid file, start, stop, pause, resume, and more functions.  when you start your daemon it detaches completely from your terminal and runs in the background.  Works very simply with monit straight out of the box.  you can have as many daemons as you wish in the same directory and they wont clobber each other (as the pid, control, and log files all are dynamically keyed off of the original script name.)  Furthermore inside your execution loop inside of the payload function place a checkforterm call at any place which it makes sense for your script to be paused, or stopped. it can detect stale pid files and run anyway if the process isnt really running.  As an added bonus you dont actually have to loop inside payload, you can put any thing in there, have a script thats not a daemon, but will take an hour, day, week, month to finish? stick it in, run it, and forget it.

8 thoughts on “As Close to A Real Daemon As Bash Scripts Get

  1. I was just busy daemonizing a script and noting a "TODO pid file" when I came across this. Thanks!

    Just to note, your function must be called "payload", the post already says this, but it didn't sink in on localhost, so to speak.

  2. So many people want to know how to write a daemon script but almost all the answers to their legitimate questions seem to be of the RTFM variety. It’s too bad that the folks who feel they must be so arrogant can’t be more helpful. You, sir, are an angel!

    The three most important concepts regarding daemonizing (is that a real word?) are looping, backgrounding and detaching and they are often not discussed in other posts.

    Thank you.

  3. Excellent – thanks.

    The only change I made was

    start)
    if [ -f $MY_PIDFILE ]; then
    echo "Daemon is already running."
    exit 0
    fi

    In cases where we want to be sure that there is only one instance of the daemon running.

  4. Makarand says:

    Hi apokalyptik ,

    I am a newbi and don't know much about scripting. Your script is very helpful, I also wanted to have this script run the command in Payload at specific date and time. Can this be achived?

    Makarand.

Leave a Reply