CHAPTER 16 - Parsing Command-Line Options - Forking

Computer Education, Training & Tutorial Resources - ComputerEducationWorld.com
Home » Free Computer Books » PHP » PHP 5 Power Programming »

Forking is UNIX lingo for making a new process by dupli-
cating an existing one. The duplicate (child) process inherits code, environ-
ment, memory (copy on write), file descriptors, and everything from the parent
process. Often, you either immediately replace the guts of the process by exe-
cuting another executable program, or close inherited file descriptors and pre-
pare the child process for its job:

Code (php)
  1.  
  2. <?php
  3.  
  4. $child_pid = pcntl_fork();
  5.  
  6. if ($child_pid == -1) {
  7.  
  8. die("pcntl_fork() failed: $php_errorstr");
  9.  
  10. } else if ($child_pid) {
  11.  
  12. printf("I am the parent, my pid is %d and my child’s pid is
  13.  
  14. %d.\n",
  15.  
  16. posix_getpid(), $child_pid);
  17.  
  18. } else {
  19.  
  20. printf("I am the child, my pid is %d.\n", posix_getpid());
  21.  
  22. }
  23.  
  24. ?>

This example demonstrates forking, creating a duplicate of the initial
process. Both processes continue running the current script from the line after
the fork. The difference is that in the parent process, the fork call returned the
process id of the child process, while in the child process the fork call returned
0. This is how you distinguish the creating and created processes.
If pcntl_fork() returns ­1, an error occurred and no process was created.


• • •
 



captcha PHP Script Free PHP captcha script free php
Website Design by WebWalas.com