How can I invoke an external shell script (Or alternatively an external PHP script) from PHP itself and get its process ID within the same script?
How can I invoke an external shell script (Or alternatively an external PHP script) from PHP itself and get its process ID within the same script?
What ended up working for me is using pgrep to get the PID of the command (or process name) executed after calling exec() in PHP.
exec($command);
$pid = exec("pgrep $command");
This will work for launching background processes too. However, you must remember to pipe the program's output to /dev/null or else PHP will hang. Also, when calling pgrep you can't include the pipe portion of the command:
$command = "bg_process -o someOption";
exec($command + " > /dev/null &"); //Separate the pipe and '&' from the command
$pid = exec("pgrep $command");
Note that if the system has multiple processes launched with the same exact command, it will return the PIDs of all processes which match the command given to pgrep. If you only pass in a process name, it will return all PIDs with that process name.