对于上下文:我正在使用xvfb-run从PHP生成一个Java应用程序。现在,这个过程为xvfb-run创建一个父PID,并为对应于Xvfb和java进程的更多子PID创建一个父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 使用:
pgrep -P 26266并且,它将返回pids如下:
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)我在这里错过了什么?任何指针都会有帮助。提前谢谢
发布于 2020-11-01 07:37:05
pgrep -P方法在PHP内部执行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 resulthttps://stackoverflow.com/questions/64561104
复制相似问题