PHP - 等待特定时间执行单行,否则返回


PHP - Wait specific time for execution of single line, otherwise return

事实上,我有一个proc_open函数,它将执行一个命令并将其子命令传送到它。这里有一个问题,有时会发生,通常不会发生。

问题

当我想获得进程管道输出时,目标服务器没有响应,脚本将等待响应直到.....

问题

我想说的是,等待响应 20 秒,如果您没有得到任何响应。 从函数返回。这很重要,我不想停止脚本执行,而只是从函数返回。
我必须使用多线程库作为 POSIX 吗?

有没有办法实现这个想法?
任何想法将不胜感激。提前致谢

代码示例

<?PHP
set_time_limit(0);
.....
public function test()
{
    foreach ($this->commands as $cmd)
    {
        fwrite($pipes[0], "$cmd 'n");   
        //Sometimes PHP stuck on the following line
        //Wait for almost 20 sec if respond did not came return
        $read = fread($pipes[1], 2096) . "'n";
    }
}

你没有说这在什么操作系统上运行,尽管你提到了POSIX。也不是哪个SAPI。总的来说,这些对您的选择有很大的影响。

此外,您

没有说您启动的过程是什么,也没有说当它超时时应该如何处理它。关闭 stdio 流可能会强制进程崩溃。如果要发送信号,则需要知道pid(IIRC在proc_open()中不可用)。

您遇到的直接问题是默认情况会阻塞读取,因此只需将其设置为非阻塞即可使您通过第一个障碍:

set_stream_blocking($pipes[1],false);
...
fwrite($pipes[0], "$cmd 'n");
$ttl=time()+20;
while(''==$read && time()<$ttl) {
   $read=fread($pipes[1],2096);
   if (!$read) sleep(1);
}
if (!$read) echo " timeout";

(顺便说一句,这可能不适用于 mswindows)

使用stream_set_timeout(但如果流相同,则在 fwrite 之后):

fwrite($pipes[0], "$cmd 'n");   
stream_set_timeout($pipes[1], 20);
$read = fread($pipes[1], 2096) . "'n";

编辑:在某些特殊情况下,您必须改用 stream_select(),对 PHP 中的错误执行操作。

$r = [$pipes[0]];
$w = $e = null;
if( stream_select($r, $w, $e, 20) !== false )
  foreach($r as $s)
    $read = fread($s,2096);

我希望这有帮助?