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 😀