The below shell script uses start-stop-daemon from “/sbin/start-stop-daemon” to execute the program during booting so that the process is started boottime. In the below example, DAEMON=$PWD/helloworld.bin shows that our program is helloworld.bin and is located in current directory from where the script is executed.
$ vim start_daemon.sh
#!/bin/sh
# Must be a valid filename
NAME=helloworld
PIDFILE=/var/run/$NAME.pid
#This is the command to be run, give the full pathname
DAEMON=$PWD/helloworld.bin
DAEMON_OPTS="--baz=quux"
export PATH="${PATH:+$PATH:}/usr/sbin:/sbin"
case "$1" in
start)
echo -n "Starting daemon: "$NAME
start-stop-daemon --start -m --background --quiet --pidfile $PIDFILE --startas $DAEMON -- $DAEMON_OPTS
echo "."
;;
stop)
echo -n "Stopping daemon: "$NAME
start-stop-daemon --stop --quiet --oknodo --pidfile $PIDFILE
echo "."
;;
restart)
echo -n "Restarting daemon: "$NAME
start-stop-daemon --stop --quiet --oknodo --retry 30 --pidfile $PIDFILE
start-stop-daemon --start -m --background --quiet --pidfile $PIDFILE --startas $DAEMON -- $DAEMON_OPTS
echo "."
;;
*)
echo "Usage: "$1" {start|stop|restart}"
exit 1
esac
exit 0
The above script can be executed as “bash start_daemon.sh start” to start the daemon.
If we want this initscript to be executed everytime during booting sequence, then we need to copy this to /etc/init.d and run the update-rc.d command once as below,
$ chmod 777 start_daemon.sh
$ sudo mv start_daemon.sh /etc/init.d/start_daemon
$ sudo update-rc.d start_daemon defaults
$ sudo reboot