Daemonize a bash script

I made a daemon process that runs all the time in background in my Debian 6 powered linux box. In this tutorial, I’m taking a example of bash script that I scripted as a temporarily fix to keep my php process up.

Enter the below code at the start of your existing bash script to create a PID a file every time it executes:

echo $$ > /var/run/phprestarter.pid;

Enter the below code at the end of your existing bash script to create run the code every 2 seconds using sleep command:

sleep 2;
/home/indude/phprestarter.sh >/dev/null 2>&1 & exit 0;

In the above line, red colored code throws away any output and doesn’t output it whereas blue colored closes the script everytime it runs. The time is entered in seconds.

Now create a new script in /etc/init.d/ directory, say “phprestarter” (without any extension) and put the following content inside it.

#! /bin/sh
# /etc/init.d/phprestarter

pid_file=/var/run/phprestarter.pid;

start_phprestarter(){
/home/indude/phprestarter.sh >/dev/null 2>&1 & exit 0;
}

case “$1” in
start)
if [ -f $pid_file ]; then
echo “PHP Restarter already running.”
else
echo “Starting PHP Restarter.”
start_phprestarter
echo “PHP Restarter is started”
fi;
exit 1;
;;
status)
if [ -f $pid_file ]; then
echo “PHP Restarter is running.”
else
echo “PHP Restarter is stopped.”
fi;
;;
restart)
echo “Restarting”
$0 stop
$0 start
echo “Restarted”
;;
stop)
echo “Stopping PHP Restarter.”
if [ -f $pid_file ]; then
kill -KILL $(cat $pid_file);
rm -f $pid_file;
fi;
exit 0;
echo “PHP Restarter Stopped.”
;;
*)
echo “Usage: /etc/init.d/phprestarter {start|stop}”
exit 1;
;;
esac

exit 0;

Change the above code with your correct paths, script names etc.

Resource: teclogs.org/how-to-running-bash-shellscripts-as-daemons-on-linux/

Leave a comment

Your email address will not be published. Required fields are marked *