Comments on Simple Bash Script To Work As A Daemon
Simple Bash Script To Work As A Daemon If you need some snippets or codes to run for ever, but not more that one instance, you need to rapidly check the code, or script and if it has died! It's the time to run it again. To be sure of this function, just add the following lock handler at the top of your script
4 Comment(s)
Comments
I'm using 'flock' for this kind of tasks. :)
http://sysadvent.blogspot.com/2008/12/day-9-lock-file-practices.html
Forgive me if I missed something but this doesn't have any code to create a bash script to run as a daemon and only included code to make sure no more than a single instance is running. Useful code for that purpuse but think subject is a bit misleading.
Or...
http://blog.apokalyptik.com/2008/05/09/as-close-to-a-real-daemon-as-bash-scripts-get/
#!/bin/bash # don't use pid's they can be doubled in theory # Under *nix, process IDs are usually allocated on a sequential basis, # beginning at 0 and rising to a maximum value which varies from system to system. # -- see: cat /proc/sys/kernel/pid_max # Once this limit is reached, allocation restarts at 300 and again increases. # meanwhile if another proccess taken your stored PID-ID you get a double but # not the assumed proccess you where looking for! # use the kernel random generator function instead, the odds of creating # a few tens of trillions of UUIDs in a year and having one duplicate uuidkey=`cat /proc/sys/kernel/random/uuid` # better use /tmp for lockfiles, gets cleaned after reboot if tmpfs is used... lockfile=/tmp/${0##*/}.lock if test -f "$lockfile" then olduuid=`cat $lockfile |awk '{print $2}'` if [ "$olduuid" == "$uuidkey" ] then # LoL, this can never be right, one chance in a ... echo "This can't be right!, the same UUID's twice" echo "new: $uuidkey" echo "old: $olduuid" else gettimestamp=`cat $lockfile |awk '{print $1}'` echo "There is a lockfile, created at: `date -d@$gettimestamp`" exit 1 fi else echo "`date +%s` $uuidkey" > $lockfile fi # got here, put the rest of the script below...