ScaleScaleScaleScale

Tips / Nginx


How to create a Linux daemon / service

linux shell

On this tutorial I will show you how to create a linux daemon / service. A Linux daemon is a script that is always running, an application that is always executing on the background and can be manipulated (start, stop, reload or restart) from the command line by the OS users. Note: on this tutorial I will use the words ‘service’ and ‘daemon’ on different times, but both means the same.

Let’s suppose you have a PHP file that needs to be executed on an infinite loop to catch some data, the best way to do this is creating a linux service. As root, create the new linux daemon:

nano -w /etc/init.d/name

Where ‘name’ is the name of your Linux service.

Paste the following content inside the new file:

#! /bin/sh

NAME=daemon_name
DESC="My first linux daemon"
PIDFILE="/var/run/${NAME}.pid"
LOGFILE="/var/log/${NAME}.log"

# PHP binary path
DAEMON="/usr/bin/php"

# Path of your php script
DAEMON_OPTS="/var/www/site.com/myscript.php"

START_OPTS="--start --background --make-pidfile --pidfile ${PIDFILE} --exec ${DAEMON} ${DAEMON_OPTS}"
STOP_OPTS="--stop --pidfile ${PIDFILE}"

test -x $DAEMON || exit 0

set -e

case "$1" in
start)
echo -n "Starting ${DESC}: "
start-stop-daemon $START_OPTS >> $LOGFILE
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon $STOP_OPTS
echo "$NAME."
rm -f $PIDFILE
;;
restart|force-reload)
echo -n "Restarting $DESC: "
start-stop-daemon $STOP_OPTS
sleep 1
start-stop-daemon $START_OPTS >> $LOGFILE
echo "$NAME."
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart|force-reload}" >&2
exit 1
;;
esac

exit 0

Remember to edit NAME, DESC and DAEMON_OPTS variables to fit your needs.

Give exec permissions to the new linux service:

chmod +x /etc/init.d/name -v

That’s all, now start your linux daemon for the first time:

service name start

 

Popular search terms:

  • linux create service
  • create linux service
  • how to create a service in linux
  • linux create a service
profile

Esteban Borges

Linux Geek, Webperf Addict, Nginx Fan. CTO @Infranetworking

  • Brahma Reddy

    Usefull !! thank you