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

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • arielCo

    #1

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

    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($p rocess))
    _echo("OK\n");
    else
    die ("not opened\n");

    _echo(print_r(p roc_get_status( $process),1));

    stream_set_bloc king($pipes[1],0);

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

    $time_limit = microtime(true) +2;
    while (true) {
    _echo(stream_ge t_contents($pip es[1]));

    $status=proc_ge t_status($proce ss);

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

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

    _echo(stream_ge t_contents($pip es[1]));
    fclose($pipes[0]);
    fclose($pipes[1]);

    _echo(print_r(p roc_get_status( $process),1));

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


    function _echo($str) {
    echo htmlspecialchar s($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

    #2
    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_writ e_buffer($pipes[0],0), to no avail.

    help!

    - Ariel

    Comment

    Working...