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

Do you have a question? Post it now! No Registration Necessary.  Now with pictures!

Threaded View

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


$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

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

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



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

$time_limit = microtime(true)+2;
while (true) {


  if (!$status['running']) {

  if (microtime(true) > $time_limit) {
    posix_kill($status['pid'], 2);  // SIGINT



$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();


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.


  --  Ariel

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

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

while ( trim($line = fgets(STDIN)) != 'exit' )

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.


- Ariel

Site Timeline