代码之家  ›  专栏  ›  技术社区  ›  Mr.Web

进程打开返回标准和从不返回标准

php
  •  0
  • Mr.Web  · 技术社区  · 6 年前

    我正在构建一个API,在我创建的类的某个点上 cmd 执行以下操作的函数:

    public function cmd($cmd)
    {
        $return_array   = [];
        $descriptorspec = array(
            0 => array("pipe", "r"), // stdin
            1 => array("pipe", "w"), // stdout
            2 => array("pipe", "w"), // stderr
        );
        //Comando, array con gli std[] e pipes
        $process = proc_open($cmd, $descriptorspec, $pipes);
    
        if (is_resource($process)) {
            //Esegue $cmd: stdin
            fputs($pipes[0], "");
            fclose($pipes[0]);
    
            //Se in risposta c'è stdout
            while ($f = fgets($pipes[1])) {
                $arr = array_push($return_array, $f);
            }
    
            fclose($pipes[1]);
            $this->good($return_array);
    
            //Se in risposta c'è stderr
            while ($f = fgets($pipes[2])) {
                $arr = array_push($return_array, $f);
            }
    
            fclose($pipes[2]);
            $this->bad($f);
    
            //Chiusura del process
            proc_close($process);
        }
    }
    

    [你可以跳过意大利语评论]

    good() bad() 函数,分别在 stdout stderr . (惊人的函数名)

    当运行这个命令(寻找一个不存在的目录)时,API返回 $this->good() :

    $this->cmd("if [ -d '/tmp/idontexist' ]; then du -s /tmp/idontexist | cut -d '\t' -f1; else echo 'directory not found' 1>&2; fi");
    

    我明白了 标准 它实际上总是存在的,所以我正在努力总结如何实现 标准错误 进入 $this->bad() 保持 标准 $this->好()

    1 回复  |  直到 6 年前
        1
  •  1
  •   Mr.Web    6 年前

    不确定这是不是问题,但在你处理 stderr ,你有。。。

    //Se in risposta c'è stderr
    while ($f = fgets($pipes[2])) {
        $arr = array_push($return_array, $f);
    }
    
    fclose($pipes[2]);
    $this->bad($f);
    

    所以这是将 标准错误 $return_array 然后你把最后一行文字 $f (只包含 false

    $this->bad($f);
    

    您可能需要使用不同的数组 stdout 正在处理,所以请尝试。。。

    //Se in risposta c'è stderr
    $errors = [];
    while ($f2 = fgets($pipes[2])) {
        array_push($errors, $f2);
    }
    
    fclose($pipes[2]);
    $this->bad($errors);
    

    编辑

    还应该检查返回的数组内容并执行 bad() good() 只有当它们真的包含某些东西时:

    fclose($pipes[1]);
    if(count($return_array)){
        $this->good($return_array);
    }
    
    //Se in risposta c'è stderr
    while ($f2 = fgets($pipes[2])) {
        $arr = array_push($errors, $f2);
    }
    
    fclose($pipes[2]);
    if(count($errors)){
        $this->bad($errors);
    }