Restarting a command line PHP script
Posted on 3/2/09 by Felix Geisendörfer
ever wrote a PHP script that acts as a daemon? No? Read Kevin's excellent post on the topic as well as this one explaining the low-level plumbing.
If you already have, you might have run into the scenario where you want the script to restart itself. For example you might have changed the code of the script after it started running, and you want to replace the current process with one running the new code.
After a bit of trial and error, I present my glorious hack:
Feel free to share your own war stories and suggestions regarding PHP scripts acting as daemons : ).
-- Felix Geisendörfer aka the_undefined
You can skip to the end and add a comment.
Felix, can you elaborate on how to use this a bit? A simple example would be great. I have the same problem. Not a daemon but just a simple php script that runs all day downloading data from a socket. Problem is, if I have to update the code, I have to restart the script and I lose data in the shutdown/restart process.
Dan: You need to determine a point (or make sure there is one) where you can shutdown your script without loosing data.
In my scenario I'm running a non-blocking IRC client that basically represents the daemon task I got running in an IRC channel and gives me updates about the work being completed. If I tell this user to '!restart' it simply executes the line from above which causes the current script to be shutdown and replaced with a fresh one using the new code.
So there isn't really anything to it but calling up that line. Everything else depends on your script.
In one application I've made some bash script (similar with .bat) that checks the exit code. In your php just make an exit(2) call.
while [ $code -eq "2" ]
Thanks Felix, I will definitely be utilizing this technique. Great blog post, funny how things appear exactly when you need them : )
I came across this post today because I was looking for a solution to the same situation.
The problem with your glorious hack is that the original php processes will hang around until finally the last one fully exits (because the call to die will wait for the return value of exec before it finally dies). This means that the resources that each script uses (most critically the RAM) will continue to be in use.
I solved the problem by using a modified version of Sebastian's bash script above. This allows the php process to exit and free all resources before the bash script re-instates the script again.
Just an FYI.
@JC What shell / OS are you using?
This post is too old. We do not allow comments here anymore in order to fight spam. If you have real feedback or questions for the post, please contact us.
I guess the '&' is the key as it makes the process run in background. Machine dependent but it is not a issue.