Re: proc_open, proc_get_status, proc_close

Arno Welzel <[email protected]> Sat, 7 Jan 2023 16:05:44 +0100
Newsgroups comp.lang.php
Message-ID <[email protected]>
Badarbo, 2023-01-06 11:29:

> Hello,
> with the code below, $rv is 0 :-)
> 
> --- begin code ---
> $pdesc=[0=>['pipe','r'],1=>['file','stdout.log','w'],2=>['file','stderr.log','w']];
> $proc=proc_open('sleep 3',$pdesc,$pipes);
> fclose($pipes[0]);
> $rv=proc_close($proc);
> echo('rv: '.$rv.PHP_EOL);
> exit(0);
> --- end code ---
[...]

Do not trust the proc-Functions in PHP to get any process results. The
did not work reliable for this in PHP 7.4 and in 8.0/8.1 I never got any
useful result from proc_close().

If you really need to be sure to get the return code of the command you
called, wrap the call in a shell command and use the result from the
wrapper, like this:

<?php
$command = 'some-command-to-execute';

$descriptors = [
	0 => ['pipe', 'r'],   // stdin
	1 => ['pipe', 'w'],   // stdout
	2 => ['pipe', 'w'],   // stderr
	3 => ['pipe', 'w'],   // file descriptor for exit code
];
$process = proc_open($command.'; echo $? >&3', $descriptors, $pipes);
if (is_resource($process)) {
	while ($output = fgets($pipes[1])) {
		$shellOutput .= $output;
	}
}
if (!feof($pipes[3])) {
	$shellResult = (int) rtrim(fgets($pipes[3], 5), "\n");
}
fclose($pipes[3]);
proc_close($process);

// $shellOutput will contain the output of stdout
// $shellResult will not contain the return code




-- 
Arno Welzel
https://arnowelzel.de