首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >从PHP中使用父PID获取儿童PID

从PHP中使用父PID获取儿童PID
EN

Stack Overflow用户
提问于 2020-10-27 18:51:59
回答 1查看 253关注 0票数 1

对于上下文:我正在使用xvfb-run从PHP生成一个Java应用程序。现在,这个过程为xvfb-run创建一个父PID,并为对应于Xvfbjava进程的更多子PID创建一个父PID。

使用以下命令,我成功地获得了(xvfb-run的)父PID:

代码语言:javascript
复制
$cmd1 = 'nohup xvfb-run -a java -jar some.jar > /dev/null 2>&1 & echo $!';
$res1 = trim(shell_exec($cmd1));

var_dump($res1);  // Returns the parent PID. For eg: 26266

现在,一旦Java进程完成,我将需要终止Java进程,以释放我的服务器资源。(Java应用程序是基于GUI的,我设法使它在不使用GUI控制的情况下工作,但我仍然可以关闭它,只能使用kill -9 <pid> )。

现在,从终端,I can get the Children 使用:

代码语言:javascript
复制
pgrep -P 26266

并且,它将返回pids如下:

代码语言:javascript
复制
26624
26633

但是,当我尝试使用PHP进行同样的操作时,我无法得到这些pid。我尝试过execshell_execsystem等。我尝试的脚本是:

代码语言:javascript
复制
$cmd2 = 'pgrep -P ' . $res1;
var_dump($cmd2);
$res2 = trim(exec($cmd2, $o2, $r2));
var_dump($res2);
var_dump($o2);
var_dump($r2);

它打印出以下内容:

代码语言:javascript
复制
string(14) "pgrep -P 26266" string(0) "" array(0) { } int(1)

我在这里错过了什么?任何指针都会有帮助。提前谢谢

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-11-01 07:37:05

pgrep -P方法在PHP内部执行exec时不起作用。因此,我使用another approach来获取子程序pid:

代码语言:javascript
复制
ps --ppid <pid of the parent>

示例PHP代码如下:

代码语言:javascript
复制
// Get parent pid and children pid in an array
$pids = [3551]; // Add parent pid here. Eg: 3551

// Call the bash command to get children pids and store in $ps_out variable
exec('ps --ppid ' . $pids[0], $ps_out);

// Loop and clean up the exec response to extract out children pid(s)
for($i = 1; $i <= count($ps_out) - 1; $i++) {
    $pids[] = (int)(preg_split('/\s+/', trim($ps_out[$i]))[0]);
}

var_dump($pids); // Dump to test the result
票数 -1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64561104

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档