As Close to A Real Daemon As Bash Scripts Get

Gravatar
Posted by apokalyptik

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.

2 Responses

  1. Ken Riley says:

    Thanks for the fantastic script! I’ve created a version that works on the Mac that’s available here:

    http://www.nodots.com/mac-daemon-functions.sh

    In addition to the script, users will need to install proctools to get a Mac version of pgrep:

    $ sudo port install proctools

    Best regards,
    Ken

  2. apokalyptik says:

    awesome! thanks!

Trackback URL for this entry