gpt4 book ai didi

php - feof 产生死循环

转载 作者:可可西里 更新时间:2023-10-31 23:47:22 24 4
gpt4 key购买 nike

所以我做了一件简单的事情,首先我通过 ssh2_exec 执行命令(在成功验证后),然后读取变量中的答案。下面是我的代码(没有验证)

try {
$stdout_stream = ssh2_exec($this->connection, $_cmd);
$stderr_stream = ssh2_fetch_stream($stdout_stream, \SSH2_STREAM_STDERR);
} catch (Exception $e) {
$std_output = $e->getMessage();
return false;
}

$output = "";

while (!feof($stdout_stream)) {
$output .= fgets($stdout_stream, 4096);
}

while (!feof($stderr_stream)) {
$output .= fgets($stderr_stream, 4096);
}

fclose($stdout_stream);
fclose($stderr_stream);

return $output;

例如我尝试执行这样的命令:

sudo service httpd stop && sudo service httpd start

所以当命令执行良好时,一切都很好,响应是

Shutting down httpd: [ OK ]Starting httpd: [ OK ]

但是当我尝试在没有 sudo 的情况下执行这样的命令时

service httpd stop && service httpd start

我知道服务器说“找不到命令”之类的东西,但我无法得到这个错误,这个脚本会无限执行。

我尝试以这种方式(或其他类似方式)重写我的代码

    $dataString = fgets($stdout_stream);
if($dataString == "\n" || $dataString == "\r\n" || $dataString == "") {
//var_dump("Empty line found.");
}

if($dataString === false && !feof($stdout_stream)) {
//var_dump("not string");
} elseif($dataString === false && feof($stdout_stream)) {
//var_dump("We are at the end of the file.\n");
break;
} else {
//else all is good, process line read in
$output .= $dataString;
}
}

但结果是一样的。

所以问题是我们不能提前说出是什么导致无限循环 $stdout_stream$stderr_stream

我正在使用 PHP 5.3。

最佳答案

我决定相信这对我的服务器来说足够 ~2 秒 来检查是否存在错误。并以防万一为第二个循环设置最长时间。所以我的代码如下。它执行的比我想要的多...

    try {
$stdout_stream = ssh2_exec($this->connection, $_cmd);
$stderr_stream = ssh2_fetch_stream($stdout_stream, \SSH2_STREAM_STDERR);
} catch (Exception $e) {
$std_output = $e->getMessage();
return false;
}

$output = "";

$start_time = time();
$max_time = 2; //time in seconds

while(((time()-$start_time) < $max_time)) {
$output .= fgets($stderr_stream, 4096);
}

if(empty($output)) {
$start_time = time();
$max_time = 10; //time in seconds

while (!feof($stdout_stream)) {
$output .= fgets($stdout_stream, 4096);
if((time()-$start_time) > $max_time) break;
}
}

fclose($stdout_stream);
fclose($stderr_stream);

return $output;

关于php - feof 产生死循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29824229/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com