Re: proc_open, proc_get_status, proc_close

"J.O. Aho" <[email protected]> Fri, 6 Jan 2023 17:35:08 +0100
Newsgroups comp.lang.php
Message-ID <[email protected]>
On 06/01/2023 11.29, Badarbo wrote:

> With the code below, $rv is -1 :-(
> 
> --- begin code ---
> $pdesc=[0=>['pipe','r'],1=>['file','stdout.log','w'],2=>['file',stderr.log','w']];
> $proc=proc_open('sleep 3',$pdesc,$pipes);
> $done=false;
> while ($done===false) {
> 	$pstat=proc_get_status($proc);
> 	if (!$pstat['running']) $done=true;
> 	usleep(500000);
> }
> fclose($pipes[0]);
> $rv=proc_close($proc);
> echo('rv: '.$rv.PHP_EOL);
> exit(0);
> --- end code ---
> 
> Why oh why?
> 
I guess it's as Arne already pointed out the second comment on 
proc_get_status() that has deciphered the "The exit code returned by the 
process (which is only meaningful if running is false). Only first call 
of this function return real value, next calls return -1."
So as long as you don't try to get the status you will get it when you 
run proc_close, if you use proc_get_status you will need to keep track 
of the status code yourself by storing in a variable that you can access 
when you execute proc_close, here is a simple fix where we have the 
latest $pstat with the correct exit code:

--- start of file ---
$pdesc=[0=>['pipe','r'],1=>['file','stdout.log','w'],2=>['file','stderr.log','w']];
$proc=proc_open('sleep 3',$pdesc,$pipes);

do {
	$pstat=proc_get_status($proc);
	usleep(500000);
} while($pstat['running']);

fclose($pipes[0]);
$rv=proc_close($proc);
echo('rv: '.$rv.', exit code: '.$pstat['exitcode'].PHP_EOL);
--- eof ---

Keep in mind that if you have another "$pstat=proc_get_status($proc);" 
any where between the end of the do-while loop and proc_close, then the 
$pstat['exitcode'] would be -1 too.

-- 
  //Aho