HomePHP Page 4 - Managing Standalone Scripts in PHP
Writing Daemons - PHP
Last week, we began our discussion of PHP standalone scripts. This week, we'll be talking about child processes, shared resources, signals, and writing daemons. The second of three parts, this article is excerpted from chapter five of the book Advanced PHP Programming, written by George Schlossnagle (Sams; ISBN: 0672325616).
A daemon is a process that runs in the background, which means that once it is started, it takes no input from the user's terminal and does not exit when the user's session ends. Once started, daemons traditionally run forever (or until stopped) to perform recurrent tasks or to handle tasks that might last beyond the length of the user's session. The Apache Web server, sendmail, and the cron daemon crond are examples of common daemons that may be running on your system. Daemonizing scripts is useful for handling long jobs and recurrent back-end tasks.
To successfully be daemonized, a process needs to complete the two following tasks:
In addition, a well-written daemon may optionally perform the following:
Setting its working directory
You learned about process detachment earlier in this chapter, in the section "Creating and Managing Child Processes." The logic is the same as for daemonizing processes, except that you want to end the parent process so that the only running process is detached from the shell. To do this, you execute pnctl_fork() and exit if you are in the parent process (that is, if the return value is greater than zero).
In Unix systems, processes are associated with process groups, so if you kill the leader of a process group, all its associates will terminate as well. The parent process for everything you start in your shell is your shell's process. Thus, if you create a new process with fork() and do nothing else, the process will still exit when you close the shell. To avoid having this happen, you need the forked process to disassociate itself from its parent process. This is accomplished by calling pcntl_setsid(), which makes the calling process the leader of its own process group.
Finally, to sever any ties between the parent and the child, you need to fork the process a second time. This completes the detachment process. In code, this detachment process looks like this:
# process is now completely daemonized
It is important for the parent to exit after both calls to pcntl_fork(); otherwise, multiple processes will be executing the same code.
Please check back next week for the conclusion of this article.