Page 1 of 1

Process fread hang on STDOUT

Posted: Thu Apr 09, 2009 7:53 pm
by onetoomanysodas
Let's say I have the following:

Code: Select all

 
$cmd = "java helloWorld";
$spec = array(0=>array('pipe','r'), 1=>array('pipe','w'), 2=>array('error-output.txt','a'));
$prc = proc_open($cmd, $spec, $pipe, getcwd());
    
if(is_resource($prc)) {
    ob_start();
    while(!feof($pipe[1])) {
        usleep(1000);
        $out = fread($pipe[1], 128);
 
        if(strlen($out)==0) {
            break;
        }
        else if($out == "\r\n") {
            echo "\r\n";
            ob_flush(); flush();
            break;
        }
        echo $out;
        ob_flush(); flush();
    }
}
 
and helloWorld.class was compiled from a source that looks like this:

Code: Select all

 
public class helloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!");
    }
}
 
Running on Windows XP, the proc_open function will use cmd.exe to execute the command.
$pipe[1] is STDOUT and the while loop will break when the newline sequence is printed.
This works because java's System.out.println function prints the string "Hello, World!" and then outputs "\r\n".

However, If it weren't for this delimiter, fread would hang because it never finds an EOF character.

I have tried using stream_set_timeout on $pipe[1] but it does not make a difference. Why can't I make the stream timeout or prevent the reading from continuing after there is nothing left to buffer in STDOUT?