赞
踩
- $pid = pcntl_fork();
- if ($pid == -1) {
- die('could not fork');
- } else if ($pid) {
- // we are the parent
- pcntl_wait($status); //Protect against Zombie children
- } else {
- // we are the child
- }
通过pcntl_fork创建一个子进程,如果返回值是-1的话,那么说明子进程创建失败.创建成功的进程id会返回给父进程,0返回给子进程.不好理解吧,费了很常时间明白以后,笔者习惯这样写:
- $pid = pcntl_fork();
- if($pid == -1){
- //创建失败咱就退出呗,没啥好说的
- die('could not fork');
- }
- else{
- if($pid){
- //从这里开始写的代码是父进程的,因为写的是系统程序,记得退出的时候给个返回值
- exit("I am parent!");
- }
- else{
- //从这里开始写的代码都是在新的进程里执行的,同样正常退出的话,最好也给一个返回值
- exit("I am child");
- }
- }
- <?php
- foreach ($tasks as $v)
- {if (($pid=pcntl_fork())===-1)
- {//...
- continue;
- }
- else if ($pid)
- {pcntl_wait($status, WNOHANG); //protect against zombie children, one wait vs one child
- }
- else if ($pid===0)
- {ob_start();//prevent output to main process
- register_shutdown_function(create_function('$pars', 'ob_end_clean();posix_kill(getmypid(), SIGKILL);'), array());//to kill self before exit();, or else the resource shared with parent will be closed
- //...
- exit();//avoid foreach loop in child process
- }
- }
- ?>
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。