CHAPTER 16 - Parsing Command-Line Options - Forking

25 views

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:

  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.



« CHAPTER 16 - Parsing Command-Line Options 2 CHAPTER 16 - Parsing Command-Line Options - Exec »
Posted on Thursday, June 7th, 2007 at 1:36 pm under PHP 5 Power Programming | RSS 2.0 Feed

Post Comment

You must be logged in to post a comment.



ComputerEducationWorld.com All Rights Reserved © RSS | CBSE | Education Boards Of India | What is My IP?