如何使用PHP生成并发进程?

Dan*_*ein 6 php proc-open

I'm trying to spawn multiple processes at once in PHP with proc_open, but the second call won't start until the first process has ended. Here's the code I'm using:

for ($i = 0; $i < 2; $i++)
{
    $cmdline = "sleep 5";
    print $cmdline . "\n";
    $descriptors = array(0 => array('file', '/dev/null', 'r'), 
                         1 => array('file', '/dev/null', 'w'), 
                         2 => array('file', '/dev/null', 'w'));
    $proc = proc_open($cmdline, $descriptors, $pipes);
    print "opened\n";
}
Run Code Online (Sandbox Code Playgroud)

Bra*_*ley 6

其他人指出了替代方案,但您的实际问题可能是您的$ proc变量泄漏.我相信PHP必须跟踪这个,如果你要覆盖它,它会为你清理(这意味着proc_close,这意味着等待......)

尽量不要泄漏$ proc值:

<?php
$procs = array();
for ($i = 0; $i < 2; $i++)
{
  $cmdline = "sleep 5";
  print $cmdline . "\n";
  $descriptors = array(0 => array('file', '/dev/null', 'r'),
    1 => array('file', '/dev/null', 'w'),
    2 => array('file', '/dev/null', 'w'));
  $procs[]= proc_open($cmdline, $descriptors, $pipes);
  print "opened\n";
}
?>
Run Code Online (Sandbox Code Playgroud)

注意:这仍将在退出之前清理您的流程句柄,因此所有流程都必须先完成.proc_close在完成这些操作后,您应该使用它们(即:读取管道等).如果您真正想要的是启动它们而忘记它们,那就是另一种解决方案.