Skip to content

Instantly share code, notes, and snippets.

@tilfin
Created Feb 21, 2013
Embed
What would you like to do?
Daemon program control script example (bash)
#!/bin/bash
prgfile=<Program Script filepath>
pidfile=<PID filepath>
start() {
if [ -f $pidfile ]; then
pid=`cat $pidfile`
kill -0 $pid >& /dev/null
if [ $? -eq 0 ]; then
echo "Daemon has started."
return 1
fi
fi
$prgfile
if [ $? -eq 0 ]; then
echo "Daemon started."
return 0
else
echo "Failed to start daemon."
return 1
fi
}
stop() {
if [ ! -f $pidfile ]; then
echo "Daemon not started."
return 1
fi
pid=`cat $pidfile`
kill $pid >& /dev/null
if [ $? -ne 0 ]; then
echo "Operation not permitted."
return 1
fi
echo -n "Stopping daemon..."
while true
do
kill -0 $pid >& /dev/null
if [ $? -ne 0 ]; then
break
fi
sleep 3
echo -n "."
done
echo -e "\nDaemon stopped."
return 0
}
status() {
if [ -f $pidfile ]; then
pid=`cat $pidfile`
kill -0 $pid >& /dev/null
if [ $? -eq 0 ]; then
echo "Daemon running. (PID: ${pid})"
return 0
else
echo "Daemon might crash. (PID: ${pid} file remains)"
return 1
fi
else
echo "Daemon not started."
return 0
fi
}
restart() {
stop
if [ $? -ne 0 ]; then
return 1
fi
sleep 2
start
return $?
}
case "$1" in
start | stop | status | restart)
$1
;;
*)
echo "Usage: $0 {start|stop|status|restart}"
exit 2
esac
exit $?
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment