Runtime Exec stop unexpectedly

2019-07-20 14:24发布

问题:

I have a little executable program in C that produce a lot of output to a file. When I call this program with Runtime, like this:

Runtime r = Runtime.getRuntime();
Process p = null;

p = r.exec("./my_program -in input.file -out output.file", null, new File(System.getProperty("java.io.tmpdir")));

When the program produce low output everything is ok, but when I call "*my_program*" with a large input it will produce a large quantity of output to the output.file, but in this case my program in Java freeze and nothing happen...

I test "*my_program*" in terminal with a lot of large inputs and everything is ok, but when I call the program in Java with Runtime.exec, the Java program freeze.

-- Thanks in advance

回答1:

Make sure you're reading from the Process's .getOutputStream() and .getErrorStream() if you aren't already. Looking at your code snippet, it appears that you're just executing .exec(...) (and maybe waiting for it to complete with a call not shown to .waitFor()?).

Per http://download.oracle.com/javase/6/docs/api/java/lang/Process.html (emphasis added):

The parent process uses these streams to feed input to and get output from the subprocess. 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.