在proc_open之后获取真正的退出代码

Dan*_*ley 7 php pipe process exit-code

proc_open在php中使用启动子进程并来回发送数据.

在某些时候,我想等待进程结束并检索退出代码.

问题是如果进程已经完成,我的调用proc_close返回-1.对于proc_close实际返回的内容显然存在很多混淆,我还没有找到一种方法来可靠地确定打开的进程的退出代码proc_open.

我已经尝试过使用了proc_get_status,但是当进程已经退出时,它似乎也会返回-1.


更新

我不能proc_get_status曾经给我一个有效的退出代码,无论它是如何调用或时.它完全坏了吗?

小智 10

我的理解是proc_close永远不会给你一个合法的退出代码.

您只能在进程结束第一次运行获取合法的退出代码.这是一个我偷走了php.net用户贡献笔记的流程类.您的问题的答案在is_running()方法中:proc_get_status

<?php
class process {

    public $cmd = '';
    private $descriptors = array(
            0 => array('pipe', 'r'),
            1 => array('pipe', 'w'),
            2 => array('pipe', 'w')
        );
    public $pipes = NULL;
    public $desc = '';
    private $strt_tm = 0;
    public $resource = NULL;
    private $exitcode = NULL;

    function __construct($cmd = '', $desc = '')
    {
        $this->cmd = $cmd;
        $this->desc = $desc;

        $this->resource = proc_open($this->cmd, $this->descriptors, $this->pipes, NULL, $_ENV);

        $this->strt_tm = microtime(TRUE);
    }

    public function is_running()
    {
        $status = proc_get_status($this->resource);

        /**
         * proc_get_status will only pull valid exitcode one
         * time after process has ended, so cache the exitcode
         * if the process is finished and $exitcode is uninitialized
         */
        if ($status['running'] === FALSE && $this->exitcode === NULL)
            $this->exitcode = $status['exitcode'];

        return $status['running'];
    }

    public function get_exitcode()
    {
        return $this->exitcode;
    }

    public function get_elapsed()
    {
        return microtime(TRUE) - $this->strt_tm;
    }
}
Run Code Online (Sandbox Code Playgroud)

希望这可以帮助.