I need to run a php script as daemon process (wait for instructions and do stuff). cron job will not do it for me because actions need to be taken as soon as instruction arrives. I know PHP is not really the best option for daemon processes due to memory management issues, but due to various reasons I have to use PHP in this case. I came across a tool by libslack called Daemon (http://libslack.org/daemon) it seems to help me manage daemon processes, but there hasn't been any updates in the last 5 years, so I wonder if you know some other alternatives suitable for my case. Any information will be really appreciated.
Answers
- create a batch file to run your php script using php executable "C:wampphpphp.exe C:wampwwwindex.php"
- add this batch file in Scheduled Task in Windows control panel.
Assuming your daemon has some way of continually running (some event loop, twisted, whatever), you can try to use upstart
.
Here's an example upstart config for a hypothetical Python service:
description "My service"
author "Some Dude <blah@foo.com>"
start on runlevel [234]
stop on runlevel [0156]
chdir /some/dir
exec /some/dir/script.py
respawn
If you save this as script.conf to /etc/init
you simple do a one-time
$ sudo initctl reload-configuration
$ sudo start script
You can stop it with stop script
. What the above upstart conf says is to start this service on reboots and also restart it if it dies.
As for signal handling - your process should naturally respond to SIGTERM
. By default this should be handled unless you've specifically installed your own signal handler.
myscript.php &
This will run the scriptin the background
you can check it with
ps aux | grep myscript.php
As Patrick has mentioned in the comments below, there is no maximum execution time for PHP scripts run from command line. myscript.php
will run indefinitely.
The BSD daemon() function is very limited and invites misuse. Only very few daemons may use this function correctly.
The systemd man pages have a list of what a correctly written SysV daemon should do when daemonizing:
http://0pointer.de/public/systemd-man/daemon.html
You could start your php script from the command line (i.e. bash) by using
nohup php myscript.php &
the
&
puts your process in the background.Edit:
Yes, there are some drawbacks, but not possible to control? That's just wrong.
A simple
kill processid
will stop it. And it's still the best and simplest solution.