Created
December 23, 2016 16:20
-
-
Save jbriard/b83ff9eef4d97808c6ef641e03d7a039 to your computer and use it in GitHub Desktop.
Daemonized bash script
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/bin/bash | |
set -e | |
PIDFILE="daemon.pid" | |
LOCKFILE="daemon.lock" | |
LOGFILE="daemon.log" | |
SELF=$0 | |
ACTION=$1 | |
ARGS="$*" | |
function _help() { | |
echo "Usage: $SELF (run|start|status|stop|help)" | |
echo "" | |
echo " run run the program" | |
echo " start run the program as daemon" | |
echo " status status of the running program" | |
echo " stop stop the running program" | |
echo " help display this message" | |
} | |
function _clean() { | |
echo "Cleaning $LOCKFILE" >> $LOGFILE | |
rm -f $LOCKFILE $PIDFILE | |
exit | |
} | |
function _exit() { | |
echo "Exited" >> $LOGFILE | |
_clean | |
} | |
function _sigterm() { | |
echo "Recived SIGTERM" >> $LOGFILE | |
_clean | |
} | |
function _sigkill() { | |
echo "Recived SIGKILL" >> $LOGFILE | |
_clean | |
} | |
function _run() { | |
(flock -e -n 9 || exit 1 | |
trap _exit EXIT | |
trap _sigterm SIGTERM | |
trap _sigkill SIGKILL | |
echo $BASHPID >> $PIDFILE | |
_main | |
) 9> $LOCKFILE | |
} | |
function _is_started() { | |
[ ! -e "$PIDFILE" ] && return 1 | |
ps -Ao pid | grep "$(cat $PIDFILE)" > /dev/null | |
return $? | |
} | |
function _status() { | |
if _is_started; then | |
echo "Started" | |
else | |
echo "Stoped" | |
fi | |
} | |
function _start() { | |
if _is_started; then | |
echo "Already started" | |
return | |
fi | |
nohup $SELF run &>> $LOGFILE & | |
sleep 1 | |
_status | |
} | |
function _stop() { | |
if ! _is_started; then | |
echo "Not started" | |
return | |
fi | |
kill $(cat $PIDFILE) | |
sleep 1 | |
_status | |
} | |
function _main() { | |
while true; do | |
echo "ping $(date +%F_%T)" | |
sleep 1 | |
done | |
} | |
case $ACTION in | |
run ) | |
_run | |
;; | |
start ) | |
_start | |
;; | |
stop ) | |
_stop | |
;; | |
status ) | |
_status | |
;; | |
*) | |
_help | |
;; | |
esac |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment