如何使用 PHP 生成并发进程?
我试图使用 proc_open 在 PHP 中一次生成多个进程,但第二个调用只有在第一个进程结束后才会启动。这是我正在使用的代码:
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";
}
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";
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
其他人指出了替代方案,但您的实际问题可能是 $proc 变量的泄漏。我相信 PHP 必须跟踪这一点,如果您覆盖它,它会为您清理(这意味着 proc_close,这意味着等待...)
尝试不要泄漏 $proc 值:
注意 :这仍然会在退出之前清理进程句柄,因此所有进程都必须首先完成。在完成您需要对这些进行的操作(即:读取管道等)后,您应该使用 proc_close 。如果您真正想要的是启动它们并忘记它们,那是一个不同的解决方案。
Others are pointing out alternatives, but your actual problem is likely the leaking of your $proc variable. I believe PHP has to keep track of this and if you are overwriting it, it will clean up for you (which means proc_close, which means waiting...)
Try not leaking the $proc value:
Note: This will still clean up your process handles before exiting, so all processes will have to complete first. You should use
proc_close
after you are done doing whatever you need to do with these (ie: read pipes, etc). If what you really want is to launch them and forget about them, that is a different solution.看看这个:
http://www.php.net/manual/en/book.pcntl。 php
See this:
http://www.php.net/manual/en/book.pcntl.php
这是一篇关于创建线程的精彩小文章。它包括一个类以及如何使用它。
http://www.alternateinterior.com/2007/ 05/multi-threading-strategies-in-php.html
这应该会让你朝着正确的方向前进。
Here is a great little article about creating threads. It includes a class and how to use it.
http://www.alternateinterior.com/2007/05/multi-threading-strategies-in-php.html
That should get you going in the right direction.
我认为这是“proc_open”设计的工作方式(实际上是系统)。您需要指定您想要使用 & 断开连接。或者通过实际运行一个 shell 脚本来运行子程序并返回给您。
I think it's way "proc_open" is design to work (actually the system). You need to specify you want to disconnect with & or by actually running a shell script which will run the sub-program and return to you.
试试这个:
Try this: