ssplyh 发表于 2017-4-7 10:07:12

PHP中利用pcntl进行多进程并发控制

  pcntl_fork可以很方便的创建进程,对于一般的需要固定的多进程处理的应用场景来说,实现比较简单,但是,对于需要大量并发创建子进程的应用场景来说,主要的问题在于会产生大量的僵尸进程。。。
  我们的应用中,之前是采用将过程中产生的子进程pid收集起来, 间隔一定时间统一回收(pcntl_waitpid),这样带来的一个问题是:在大量并发情况下,服务器压力过大,会导致子进程“死掉”,这个时候,子进程不是僵尸,无法回收掉,主控进程就卡在那里不动了。。。
  今天借鉴了一下“http://www.perkiset.org/forum/php/forked_php_daemon_example-t474.0.html”文中的方式,用二次创建进程的方式(孙进程处理业务)来将子进程交给系统,达到了在父进程中不需要wait真正的业务子进程的目的,也更接近其他语言中的线程并发控制:
  我们原来的子进程创建接口:
  /*** author: selfimpr* blog: http://blog.csdn.net/lgg201* mail: lgg860911@yahoo.com.cn*/function new_child($func_name) {$args = func_get_args();unset($args);$pid = pcntl_fork();if($pid == 0) {function_exists($func_name) and exit(call_user_func_array($func_name, $args)) or exit(-1);} else if($pid == -1) {echo "Couldn’t create child process.";} else {return $pid;}}
  新的方式:
  <?php/*** author: selfimpr* blog: http://blog.csdn.net/lgg201* mail: lgg860911@yahoo.com.cn*/function daemon($func_name) {$args = func_get_args();unset($args);$pid = pcntl_fork();if($pid) {pcntl_wait($status);} else if($pid == -1) {echo "Couldn't create child process.";} else {$pid = pcntl_fork();if($pid == 0) {posix_setsid();function_exists($func_name) and exit(call_user_func_array($func_name, $args)) or exit(-1);} else if($pid == -1) {echo "Couldn’t create child process.";} else {exit;}}}?>
  新方式的完整测试:
  测试方法:cli模式下运行, ps -ef | grep php查看过程中的php进程情况
  <?php/*** author: selfimpr* blog: http://blog.csdn.net/lgg201* mail: lgg860911@yahoo.com.cn*/function daemon($func_name) {$args = func_get_args();unset($args);$pid = pcntl_fork();if($pid) {pcntl_wait($status);} else if($pid == -1) {echo "Couldn't create child process.";} else {$pid = pcntl_fork();if($pid == 0) {posix_setsid();function_exists($func_name) and exit(call_user_func_array($func_name, $args)) or exit(-1);} else if($pid == -1) {echo "Couldn’t create child process.";} else {sleep(5);exit;}}}function test() {while($i ++ < 10) {echo "child process $i/n";sleep(1);}}daemon(test);while(++ $j) echo "parent process $j/n";?>
页: [1]
查看完整版本: PHP中利用pcntl进行多进程并发控制