2011/03/05

Java java.lang.Process#waitFor Does Not Return

According to the Java DOC:
Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.

A simple pair of programs are provided to experiment above statements.


large.pl
#!/usr/bin/perl

use strict;
use warnings;

my @large = 1..100_000;
print "@large\n";

BadExecJavac2.java
import java.util.*;
import java.io.*;

public class BadExecJavac2
{
    public static void main(String args[])
    {
        try
        {           
            Runtime rt = Runtime.getRuntime();
            Process proc = rt.exec("perl large.pl");
            int exitVal = proc.waitFor();
            System.out.println("Process exitValue: " + exitVal);
        } catch (Throwable t) {
            t.printStackTrace();
        }
    }
}

Compile BadExecJava2.java and execute it, and you will find it never returns.
Replace 100_000 in large.pl with a smaller value, say, 1000, and then BadExecJava2 works well and returns.