Home arrow PHP arrow Page 2 - Managing Standalone Scripts in PHP

Closing Shared Resources - 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).

  1. Managing Standalone Scripts in PHP
  2. Closing Shared Resources
  3. Signals
  4. Writing Daemons
By: Sams Publishing
Rating: starstarstarstarstar / 10
September 07, 2006

print this article



When you fork a process in the Unix environment, the parent and child processes both have access to any file resources that are open at the time fork() was called. As convenient as this might sound for sharing resources between processes, in general it is not what you want. Because there are no flow-control mechanisms preventing simultaneous access to these resources, resulting I/O will often be interleaved. For file I/O, this will usually result in lines being jumbled together. For complex socket I/O such as with database connections, it will often simply crash the process completely.

Because this corruption happens only when the resources are accessed, simply being strict about when and where they are accessed is sufficient to protect yourself; however, it is much safer and cleaner to simply close any resources you will not be using immediately after a fork.

Sharing Variables

Remember: Forked processes are not threads. The processes created with pcntl_fork() are individual processes, and changes to variables in one process after the fork are not reflected in the others. If you need to have variables shared between processes, you can either use the shared memory extensions to hold variables or use the "tie" trick from Chapter 2, "Object-Oriented Programming Through Design Patterns."

Cleaning Up After Children

In the Unix environment, a defunct process is one that has exited but whose status has not been collected by its parent process (this is also called reaping the child process). A responsible parent process always reaps its children.

PHP provides two ways of handing child exits:

  • pcntl_wait($status, $options)pcntl_wait() instructs the calling process to suspend execution until any of its children terminates. The PID of the exiting child process is returned, and $status is set to the return status of the function.

  • pcntl_waitpid($pid, $status, $options)pcntl_waitpid() is similar to pcntl_wait(), but it only waits on a particular process specified by $pid. $status contains the same information as it does for pcntl_wait().

For both functions, $options is an optional bit field that can consist of the following two parameters:

  • WNOHANG—Do not wait if the process information is not immediately available.

  • WUNTRACED—Return information about children that stopped due to a SIGTTIN, SIGTTOU, SIGSTP, or SIGSTOP signal. (These signals are normally not caught by waitpid().)

Here is a sample process that starts up a set number of child processes and waits for them to exit:

#!/usr/bin/env php
define('PROCESS_COUNT', '5');
$children = array();
for($i = 0; $i < PROCESS_COUNT; $i++) {
if(($pid = pcntl_fork()) == 0) {
else {
$children[] = $pid;
foreach($children as $pid) {
$pid = pcntl_wait($status);
if(pcntl_wifexited($status)) {
$code = pcntl_wexitstatus($status);
print "pid $pid returned exit code: $code\n";
else {
print "$pid was unnaturally terminated\n";
function child_main()
$my_pid = getmypid();
print "Starting child pid: $my_pid\n";
return 1;

One aspect of this example worth noting is that the code to be run by the child process is all located in the function child_main(). In this example it only executes sleep(10), but you could change that to more complex logic.

Also, when a child process terminates and the call to pcntl_wait() returns, you can test the status with pcntl_wifexited() to see whether the child terminated because it called exit() or because it died an unnatural death. If the termination was due to the script exiting, you can extract the actual code passed to exit() by calling pcntl_wexitstatus($status). Exit status codes are signed 8-bit numbers, so valid values are between –127 and 127.

Here is the output of the script if it runs uninterrupted:

> ./5.php
Starting child pid 4451
Starting child pid 4452
Starting child pid 4453
Starting child pid 4454
Starting child pid 4455
pid 4453 returned exit code: 1
pid 4452 returned exit code: 1
pid 4451 returned exit code: 1
pid 4454 returned exit code: 1
pid 4455 returned exit code: 1

If instead of letting the script terminate normally, you manually kill one of the children, you get output like this:

> ./5.php
Starting child pid 4459
Starting child pid 4460
Starting child pid 4461
Starting child pid 4462
Starting child pid 4463
4462 was unnaturally terminated
pid 4463 returned exit code: 1
pid 4461 returned exit code: 1
pid 4460 returned exit code: 1
pid 4459 returned exit code: 1

>>> More PHP Articles          >>> More By Sams Publishing

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort


- Hackers Compromise PHP Sites to Launch Attac...
- Red Hat, Zend Form OpenShift PaaS Alliance
- PHP IDE News
- BCD, Zend Extend PHP Partnership
- PHP FAQ Highlight
- PHP Creator Didn't Set Out to Create a Langu...
- PHP Trends Revealed in Zend Study
- PHP: Best Methods for Running Scheduled Jobs
- PHP Array Functions: array_change_key_case
- PHP array_combine Function
- PHP array_chunk Function
- PHP Closures as View Helpers: Lazy-Loading F...
- Using PHP Closures as View Helpers
- PHP File and Operating System Program Execut...
- PHP: Effects of Wrapping Code in Class Const...

Developer Shed Affiliates


Dev Shed Tutorial Topics: