What is the best way to keep a PHP script running as a daemon, and what\'s the best way to check if needs restarting.
I have some scripts that need to run 24/7 and f
The most elegant solution is reactPHP.
We run our daemons by piping the output to mail.
php daemon.php | mail -s "daemon stopped" foo@example.org
That way, when/if the daemon stops, it will send a mail, and we will be notified that way.
It still means manual restart of the daemons of course, but we'll know right away. Usually, if the daemons stopped, it means that there is something else that needs to be taken care of anyway, so that's usually ok.
I use a PHP-based script to read from a database and send emails out (using the PEAR Mail_Queue library). I run it from within a bash script and based on the returned result (from "exit $status;") either halt, sleep X seconds, or immediately restart. (I also put a check of the load average/sleep into the PHP script to avoid stressing the mail system).
If it was for a long-term daemon that had to be continually running, then I agree, it probably would not be the best thing to run this (though I have heard of some socket servers that did run successfully long term), however, PHP 5.3 does also now have improved garbage collection, and if the script is well written enough to not exit unplanned, then memory should be far less of a problem that before.
If you can't use the (proper) init structure to do this (you're on shared hosting, etc.), use cron to run a script (it can be written in whatever language you like) every few minutes that checks to see if they're running, and restarts them if necessary.
TBH, PHP probably isn't the best tool for this, really not what it was designed for. I've heard of memory leaks and other bad things happening when you try this. Also bear in mind PHP only has a finite amount of resource ids (for file handles, db connections ect) per execution of a script.
Be better of using something else, maybe python or perl, though I don't have any real experience writing these sorts of apps, but I do know PHP isn't right for what your trying to do.
Quick and dirty cron to restart your daemon:
* * * * * USER ps auxww | grep SCRIPTNAME > /dev/null || SCRIPTNAME
Replace USER with the user that the daemon runs as and SCRIPTNAME with the name of your script. Stick this in /etc/cron.d/restart_php_daemon
. It should run every minute. Change the first *
to */2
or */5
to run less frequently.
UPDATE
If you're putting this into your own crontab:
Run crontab -e
and add:
* * * * * ps auxwww | grep SCRIPTNAME > /dev/null || SCRIPTNAME