2

I am using ProcessBuilder in Java to run a Perl script. When I run the Perl script while printing the InputStream of the process, the Java program seems to run for the duration of the Perl script. However if I comment out the getOutPut method in main the Java program terminates very fast and the Perl script does not run at all. Why does this occur?

private final static String SCENARIO =  "scen"; 

/**
 * @param args
 */
public static void main(String[] args) {


    ProcessBuilder pb = new ProcessBuilder("perl", SCENARIO+".pl");
    pb.directory(new File("t:/usr/aman/"+SCENARIO));
    try {
        Process p = pb.start();
        getOutput(p.getInputStream(), true);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

private static List getOutput(InputStream is, boolean print) {
    List output = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));

    String s = null;
    try {
        while ((s = reader.readLine()) != null) {
            output.add(s);
            if(print){
                System.out.println(s);
            }
        }
        is.close();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        //e.printStackTrace();
        return null;
    }
    return output;
}
4

1 回答 1

2

Likely the OS's output stream buffer for your PERL script process gets filled because nothing is emptying this buffer, and this will kill the process. You need to gobble the output stream for this reason which is what your getOutput method does for you.

Please read the classic reference on this problem: When Runtime.exec() won't. Per this article:

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.

于 2013-04-26T21:08:53.717 回答