feof 产生无限循环

Ale*_*nov 5 php feof ssh2-exec

所以我做了一件简单的事情,首先我通过 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;
Run Code Online (Sandbox Code Playgroud)

例如我尝试执行这样的 cmd:

sudo service httpd stop && sudo service httpd start
Run Code Online (Sandbox Code Playgroud)

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

关闭 httpd: [ OK ] 启动 httpd: [ OK ]

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

service httpd stop && service httpd start
Run Code Online (Sandbox Code Playgroud)

我知道服务器说类似“找不到命令”或类似的内容,但我无法收到此错误,此脚本无限执行。

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

    $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;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但结果是一样的。

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

我正在使用 PHP 5.3。

Ale*_*nov 0

我决定相信我的服务器大约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;
Run Code Online (Sandbox Code Playgroud)