Process fread hang on STDOUT

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
onetoomanysodas
Forum Newbie
Posts: 1
Joined: Thu Apr 09, 2009 7:52 pm

Process fread hang on STDOUT

Post 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?
Post Reply