There are three Java applications, appB just launches an appC that will last forever. appA launches appB and reads its output. But appA never comes out. Anyone has an idea why this is happening and how to solve it. It does not hang unless I read the stream in appA.
I tried two ways:
- Direct access to the read stream (readViaInputStream) or BufferedReader (readViaBufferedReader).
They do not work, the output will be:
// if we call them, the main application freezes, the output will be:
// Before calling the child process
// After calling the child process
// the main program hangs here.
// Never output - "Stream reading completed."
In readViaInputStream, it hangs with the fill () method in the BufferedInputStream.fill () method with int n = getInIfOpen (). read (buffer, pos, buffer.length - pos); It calls the native method of the FileInputStream class.
The same goes for readViaBufferedReader.
- Use a different stream to read the output stream.
It also does not work, the output will be:
// Before calling the child process
// After calling the child process
// Read stream completed.
// ===> and the main program freezes
Thanks so much for any answer :)
Code below: Updated to use the Guillaume Polet code provided in the following comment.
public class MainApp { public static enum APP { B, C; } public static void main(String[] args) throws Exception, InterruptedException { if (args.length > 0) { APP app = APP.valueOf(args[0]); switch (app) { case B: performB(); break; case C: performC(); break; } return; } performA(); } private static void performA() throws Exception { String javaBin = "java"; String[] cmdArray = { javaBin, "-cp", System.getProperty("java.class.path"), MainApp.class.getName(), APP.B.name() }; ProcessBuilder builder = new ProcessBuilder(cmdArray); builder.redirectErrorStream(true); final Process process = builder.start(); process.getOutputStream().close(); process.getErrorStream().close();
}