PHP: Getting the PID of a process running in the background

skij used Ask the Experts™
This PHP code runs the $cmd in the background.   The response is written to the file $outputfile and the pid of the process is written to $pidfile.
exec(sprintf("%s > %s 2>&1 & echo $! >> %s", $cmd, $outputfile, $pidfile));

Open in new window

Instead of writing the $pidfile to a file, how can I access it in the PHP script?  Can I access it as a variable instead of writing the result to a file?
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Uros Gaberdirector
You should use proc_open and proc_get_status or popen instead, this way you have much more control over the process you start.
you can do things such as echo the pid at the beginning of the script

$p=popen('printf "$$\n" ; exec '.$cmd.' > '.$outfile,'r');


you also can spawn a separate ps or pgrep command in order to retrieve the pid


or use proc_open + proc_get_status

$descriptorspec = array(
   1 => array("file","$outfile", "w"),
   2 => array("file", "$errorfile", "a")

$process = proc_open($cmd, $descriptorspec, $pipes);

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial