Home  >  Article  >  Backend Development  >  Example of using pcntl_fork to implement PHP multi-process

Example of using pcntl_fork to implement PHP multi-process

WBOY
WBOYOriginal
2016-07-25 08:58:31868browse
  1. /home/jerry/Public/php-5.4.0/ext/pcntl
Copy code

Explanation: int pcntl_fork ( void ) The pcntl_fork() function creates a child process that is different from its parent process only in PID (process ID) and PPID (parent process ID). On success, the PID of the generated child process is returned in the parent process execution thread, and 0 is returned in the child process execution thread. On failure, -1 is returned in the parent process context, the child process is not created, and a PHP error is raised. int pcntl_wait ( int &$status [, int $options = 0 ] ) pcntl_wait — Wait for or return the child process status of fork void pcntl_exec ( string $path [, array $args [, array $envs ]] ) pcntl_exec — Execute the specified program in the current process space

Example:

  1. /**
  2. * pcntl_fork multi-process code example
  3. * edit bbs.it-home.org
  4. */
  5. $cmds=array(
  6. array('/home/jerry/projects/www/test2.php'),
  7. array('/home /jerry/projects/www/test3.php')
  8. );
  9. foreach($cmds as $cmd){
  10. $pid=pcntl_fork();
  11. if($pid==-1){
  12. //Process creation failed
  13. echo 'Return -1 when creating a child process fails';
  14. exit(-1);
  15. }
  16. else if($pid){
  17. //The parent process will get the child process number, so here is the logic executed by the parent process
  18. pcntl_wait($status,WNOHANG);
  19. }
  20. else{
  21. //Subprocess processing logic
  22. sleep(5);
  23. pcntl_exec('/usr/bin/php',$cmd);
  24. exit(0);
  25. }
  26. }
  27. ?>
Copy code


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn