Skip to content
Advertisement

Get Children PID using Parent PID from PHP

For context: I am spawning a Java application from PHP, using xvfb-run. Now, this process creates a parent PID for the xvfb-run and couple more children PIDs corresponding to Xvfb and java process.

Using the following command, I have managed to get the parent PID (of xvfb-run):

$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

Now, once the Java process is complete, I will need to kill the Java process, to free up my server resources. (Java application is GUI based, and I have managed to get it working without utilising GUI control, but still I can close it, only by using kill -9 <pid>

Now, from the terminal, I can get the Children pid using:

pgrep -P 26266

and, it will return me pids as follows:

26624
26633

However, when I try to do the same using PHP, I cannot get these pid(s) out. I have tried exec, shell_exec, system etc. My attempted script is:

$cmd2 = 'pgrep -P ' . $res1;
var_dump($cmd2);
$res2 = trim(exec($cmd2, $o2, $r2));
var_dump($res2);
var_dump($o2);
var_dump($r2);

It prints out the following:

string(14) "pgrep -P 26266" string(0) "" array(0) { } int(1)

What am I missing here ? Any pointer would be helpful. Thanks in Advance

Advertisement

Answer

pgrep -P approach did not work when doing exec inside PHP. So, I used another approach to get children pid(s):

ps --ppid <pid of the parent>

The sample PHP code would be:

// 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
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement