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

标签 php process pipe exit-code

我在 php 中使用 proc_open启动一个子进程并来回发送数据。

有时我想等待进程结束并检索退出代码

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

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


更新

我无法让 proc_get_status 给我一个有效的退出代码,无论它是如何或何时被调用的。它完全坏了吗?

最佳答案

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

您只能在第一次运行proc_get_status之后进程结束时获取合法退出代码。这是我 stole 的过程类关闭 php.net 用户贡献的注释。您的问题的答案在 is_running() 方法中:

<?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;
    }
}

希望这对您有所帮助。

关于php - 在 proc_open 之后获取真正的退出代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7645499/

相关文章:

c - 如果从管道读取时 tail 失败怎么办

java - 我如何检测 JasperViewer 处理报告时间

c++ - 使用单独的参数调用 `execve failed: No such file or directory` 时获取 `boost::process::system()`

linux - 如何使用 bash 命令列出进程使用的管道

javascript - PHP JOIN查询调整产品状态但无法解决

c - 如何从 C 中的程序关闭 gnome 终端屏幕

c - 管道系统调用

php 谷歌广告 api - unauthorized_client

PHP:如何将变量添加到函数名称?

php - 如何从其表格中恢复广告服务器的印象和点击