Connecting Tech Pros Worldwide Forums | Help | Site Map

help with proc_open(): some apps work - some don't

arielCo
Guest
 
Posts: n/a
#1: Nov 24 '05
Hello,

I'm attempting to use proc_open to launch, control and log CLI
applications from my scripts, but my first tests are disheartening:

<pre>
<?php

$descriptorspec = array(
0 => array("pipe", "r"),
1 => array("pipe", "w"),
2 => array("file", "/var/tmp/errors", "a+")
);

$cwd = '/var/tmp';
$env = array('a' => 'abc'); // otherwise some processes exit with code
127

$cmd='cat -n';
// $cmd='tr a A';
$process = proc_open($cmd, $descriptorspec, $pipes, $cwd, $env);

if (is_resource($process))
_echo("OK\n");
else
die ("not opened\n");

_echo(print_r(proc_get_status($process),1));

stream_set_blocking($pipes[1],0);

fwrite($pipes[0],"blah blah\n");
fwrite($pipes[0],"blah blah\n");

$time_limit = microtime(true)+2;
while (true) {
_echo(stream_get_contents($pipes[1]));

$status=proc_get_status($process);

if (!$status['running']) {
_echo("DIED\n");
break;
}

if (microtime(true) > $time_limit) {
_echo("TIMEOUT\n");
posix_kill($status['pid'], 2); // SIGINT
break;
}
}

_echo(stream_get_contents($pipes[1]));
fclose($pipes[0]);
fclose($pipes[1]);

_echo(print_r(proc_get_status($process),1));

$return_value = proc_close($process);
_echo("command returned $return_value\n");


function _echo($str) {
echo htmlspecialchars($str);
if (php_sapi_name()!='cli') {
ob_flush(); flush();
}
}


?>
</pre>

With 'cat -n', every line gets processed as soon as it is sent; not so
with 'tr a A' (I have to fclose(pipes[0]) for tr to process the input).
What's the difference? My ultimate goal is to run pppd, ping, wget and
others, put only ping seems to work.

regards,

-- Ariel


arielCo
Guest
 
Posts: n/a
#2: Nov 25 '05

re: help with proc_open(): some apps work - some don't


Update: a simple script like this works fine as the child process:

#!/usr/local/bin/php
<?php
while ( trim($line = fgets(STDIN)) != 'exit' )
fwrite(STDOUT,$line);
exit(0);
?>

But 'grep .' doesn't - it also requires me to fclose its stdin.
Is this about stream buffering? I've tried
stream_set_write_buffer($pipes[0],0), to no avail.

help!

- Ariel

Closed Thread