Run PHP Script As Daemon Service

Server environment

1
2
3
4
5
$ cat /etc/issue
Ubuntu 14.04.5 LTS

$ php -v
PHP 5.6.32-1+ubuntu14.04.1+deb.sury.org+2 (cli)

How to run php script as daemon process?

Nohup

1
nohup php script.php &

Upstart

1
$ sudo vim /etc/init/myphpworker.conf
1
2
3
4
5
6
7
8
9
start on startup
stop on shutdown

respawn
respawn limit 20 5

script
exec /usr/bin/php -f /app/script.php
end script

or you can check the php script if return error then stop this service

1
2
3
script
[ $(exec /usr/bin/php -f /app/script.php) = 'ERROR' ] && ( stop; exit 1; )
end script

  • If /app/script.php echo a “ERROR” string ,this service will stop

Check this service status

1
2
3
4
5
$ sudo service myphpworker status
myphpworker stop/waiting

$ sudo service myphpworker start
myphpworker start/running, process 2648

Check the script output log

1
2
3
4
$ sudo tail -f /var/log/upstart/myphpworker.log 
welcome
welcome
...

The php script demo

1
2
<?php
echo "welcome". PHP_EOL;

Supervisor

You can see my another blog

Start-stop-daemon

start-stop-daemon is a linux tool

I have wrote a demo and the demo directory is like this

1
2
3
4
5
6
7
$ pwd
/home/vagrant/start-stop-daemon

# ls -lh
total 8.0K
-rw-rw-r-- 1 vagrant vagrant 59 Jul 11 18:29 a.php
-rwxr-xr-x 1 root root 791 Jul 11 18:29 run

The run script file:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
#! /bin/sh

DAEMON=/usr/bin/php
DAEMON_OPTS='/home/vagrant/start-stop-daemon/a.php'
NAME='daemon-demo'
DESC='daemon-demo'
PIDFILE="/var/run/${NAME}.pid"
QUIET="--quiet"
START_OPTS="--start ${QUIET} --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
echo "$NAME."
;;
stop)
echo -n "Stopping $DESC: "
start-stop-daemon $STOP_OPTS
echo "$NAME."
;;
restart|force-reload)
echo -n "Restarting $DESC: "
start-stop-daemon $STOP_OPTS
sleep 1
start-stop-daemon $START_OPTS
echo "$NAME."
;;
*)
N=/etc/init.d/$NAME
echo "Usage: $N {start|stop|restart|force-reload}" >&2
exit 1
;;
esac

exit 0

Execute it:

1
2
3
4
5
6
7
8
# ./run start
Starting daemon-demo: daemon-demo.

# ./run restart
Restarting daemon-demo: daemon-demo.

# ./run stop
Stopping daemon-demo: daemon-demo.

Or you can put this script in $PATH

Share