我在 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/