How to create a daemon in linux | extrovert.dev -->

How to create a daemon in linux

How to create a daemon in linux
Saturday, October 21, 2017


In this tutorial I will show you how to create a linux daemon service script in linux. According to Wikipedia( In multitasking computer operating systems, a daemon (/ˈdmən/ or /ˈdmən/)[1] is a computer program that runs as a background process, rather than being under the direct control of an interactive user. )

Suppose you have a PHP file that needs to executed on some infinite loop 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/namename

Name is the name of your service means daemon name!

Paste the following content in a 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

Note to edit NAME, DESC and DAEMON_OPTS variables to setup your needs.

Give the permissions to the new file using chmod


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

Now you can start your daemon service

service name start


0 Response to How to create a daemon in linux

Comments are personally moderated by our team. Promotions are not encouraged.

Post a Comment