Search code examples
javawindowscommand-promptderbyprocessbuilder

Java Code stucking when attempt read output messages of Process


I use ProcessBuilder for execute the cmd commands in my application for Start & Stop Derby Network Server. But somethings going wrong and i don't find where the problem. Let me explain it;

Starting Network Server;

//Defining path of db files located
File file= new File(FirstTimeMainFrame.class.getProtectionDomain()
                        .getCodeSource()
                        .getLocation()
                        .getPath().replace(new File(FirstTimeMainFrame.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getName(), "").replace("%20", " "));

String path = file+"\\DB";

//Process Creating
ProcessBuilder builder = new ProcessBuilder();
Process process = null;
String[] command = new String[3];

command[0] = "cmd.exe";
command[1] = "/c"; //This things say to CMD close when commands complete.
command[2] = "cd "+path+" && java -jar derbyrun.jar server start";
builder = new ProcessBuilder(command[0], command[1], command[2]);
builder.redirectErrorStream(true);
process = builder.start();

//Reading CMD outputs
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
  while (true) {
     line = br.readLine();
     if (line == null) { break; }
     System.out.println(line);
  }

When i debug the project i see output for two lines and debug stuck at line = br.readLine(); when While loop come and check for third time. Whole program stuck and can't continue.

Outputs;

Fri Dec 25 20:54:36 EET 2015 : Security manager installed using the Basic server security policy.
Fri Dec 25 20:54:36 EET 2015 : Apache Derby Network Server - 10.12.1.1 - (1704137) started and ready to accept connections on port 1527

Important P.S.: If i remove //Reading CMD outputs codes all things working perfectly. Server Starting, DB Created, Tables Created etc.

Also i tried same CMD Command under Windows directly. When i execute the command, two line writed and Command Prompt window stuck at the flashing cursor (not closed or complete i think) but Derby Server is started without problem in programaticly or directly in Windows.


Solution

  • There are actually two processes running in the scenario: CMD process started from java code and Derby server process spawned by CMD.

    The output from Derby server process is directed to command line and then can be read in java code. Server process can run infinetly long until it will be terminated, that's why output stream never ends.

    Hanging in java code happens because there are no available bytes in the stream at the moment - server process told you that it was successfully initialized and then moved to waiting state.