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

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?
LVL 10
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Uros GaberdirectorCommented:
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);

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Shell Scripting

From novice to tech pro — start learning today.