如何解决使用PHP中的父级PID获取子级PID
对于上下文:我正在使用xvfb-run
从PHP生成Java应用程序。现在,此过程将为xvfb-run
创建一个父PID,并耦合与Xvfb
和java
过程相对应的更多子PID。
使用以下命令,我设法获取了{xvfb-run
的父PID:
$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 pid使用:
pgrep -P 26266
,它将返回我的pid,如下所示:
26624
26633
但是,当我尝试使用PHP执行相同操作时,无法取出这些pid。我尝试了exec
,shell_exec
,system
等。尝试的脚本是:
$cmd2 = 'pgrep -P ' . $res1;
var_dump($cmd2);
$res2 = trim(exec($cmd2,$o2,$r2));
var_dump($res2);
var_dump($o2);
var_dump($r2);
它打印出以下内容:
string(14) "pgrep -P 26266" string(0) "" array(0) { } int(1)
我在这里想念什么?任何指针都会有所帮助。在此先感谢
解决方法
在PHP中执行
pgrep -P
时, exec
方法不起作用。因此,我使用another approach来获得孩子的pid:
ps --ppid <pid of the parent>
示例PHP代码为:
// 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
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。