1

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

Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57
  • Never dealt with all these but what does `pgrep -P 27342` on the terminal give? Initially you got the result with `26266` – nice_dev Oct 27 '20 at 19:20
  • @nice_dev it was a typo. Edited. I have given dummy pid(s) for problem statement. Whatever parent pid I get, I can access the child pid(s), when I run it in terminal – Madhur Bhaiya Oct 28 '20 at 02:17
  • Does this answer your question? [Running at from PHP gives no output](https://stackoverflow.com/questions/10968661/running-at-from-php-gives-no-output) – nice_dev Oct 28 '20 at 05:06
  • @nice_dev Tried but does not work. It seems that there is some limitation with `pgrep` approach. I have managed to solve this using `ps --ppid` approach. Will add an answer soon – Madhur Bhaiya Oct 28 '20 at 06:06

1 Answers1

-1

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
Madhur Bhaiya
  • 28,155
  • 10
  • 49
  • 57