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:
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 |
<?php declare(ticks=1); $pid = pcntl_fork(); if ($pid == -1) { die("could not fork"); } else if ($pid) { exit(); // it's the parent -- lets quit } else { // it's the child -- nothing to do at the moment } // detatch from the terminal if (posix_setsid() == -1) { die("could not detach from terminal"); } // setup signal handlers pcntl_signal(SIGTERM, "sig_handler"); pcntl_signal(SIGHUP, "sig_handler"); // launch the script -- transfer the args to the child script shell_exec("php script.php {$argv[1]} {$argv[2]} {$argv[3]} "); function sig_handler($signo) { switch ($signo) { case SIGTERM: // handle shutdown tasks exit; break; case SIGHUP: // handle restart tasks break; default: // handle all other signals } } ?> |
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. 🙂
[…] ??? ???? ???????????? ????? ????? ???????? ????? * ?????? ?????????????? ????? (specification, […]
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.
sonic server daemon maybe?
http://dev.pedemont.com/sonic
[…] Running a PHP Script as a Daemon AKPC_IDS += "8788,"; Bookmark It […]