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

DESC="My first linux daemon"

# PHP binary path

# Path of your php script

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
echo -n "Starting ${DESC}: "
start-stop-daemon $START_OPTS >> $LOGFILE
echo "$NAME."
echo -n "Stopping $DESC: "
start-stop-daemon $STOP_OPTS
echo "$NAME."
rm -f $PIDFILE
echo -n "Restarting $DESC: "
start-stop-daemon $STOP_OPTS
sleep 1
start-stop-daemon $START_OPTS >> $LOGFILE
echo "$NAME."
echo "Usage: $N {start|stop|restart|force-reload}" >&2
exit 1

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
  • how to create a service in linux
  • create linux service
  • create service linux

Esteban Borges

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

  • Brahma Reddy

    Usefull !! thank you