Categories
PHP

Running a PHP Script as Daemon

For our ongoing project at Leevio, I had to find a way to run a php script as a daemon. I checked out a few techniques. I didn’t like any of them much. I needed a way to run the intended script and then exit the terminal leaving the script to keep running in the background.

After a bit of hard work, I chose to use the PCNTL functions to achieve my goal. Here’s the code I used:

Note that, in this case, the daemon quits the moment the shell_exec() command is executed. We are executing our intended PHP script as a sub process which has been detached from the terminal. The script has a while loop to keep it running forever. So, we can safely quit the main process while the forked process remains alive with the php script being executed 😀

6 replies on “Running a PHP Script as Daemon”

M, definitely a very good work. I knew about System_Daemon but this one looks really cool. Do you know if there is any OS specific issue with pcntl_fork or it is cross OS (forget abt windows – I am talking about different flavors of linux and mac os)

Keep up the good work. 🙂

I kinda like it too, but what about “nohup” in the shell. IMHO, “nohup” should keep the script running even if you exit the shell.

nohup php script.php {args} &

I had implemented a very crude daemon in PHP a while ago. The code can be found here: http://forum.projanmo.com/topic11447.html

(That code was basically translated from a simple daemon I’d written in FreePascal a long time ago – hence the code looks so un-PHP-ish and ugly 😉 ).

WRT Mr. Hasin’s comment above, I think you should implement the double-fork technique to ensure the code works reliably on all unices. I’m not familiar with darwin though, but IIRC solaris (and perhaps freebsd too) requires the double-fork. Your code (single-fork) will work fine in linux, but will fail in other unices. Please refer to the forum post for the code.

Comments are closed.