0

I have a process that creates another process. The first process waits for the second process to print "done" then continues. However, I am getting a race condition where the first process gets stuck sometimes and can't continue after the second process prints. My code is:

First Process (process is created with ProcessBuilder):

if((new BufferedReader(new InputStreamReader(process.getInputStream())).readLine()).contains("Process done"))
        {

        } 
System.out.println("Second process completed.");
process.destroy();

Second Process:

public static void main(String[] args) 
{
    /*does some action*/
    System.out.println("Process done");
    Thread.sleep(Integer.MAX_VALUE);
}

Sometimes this works, but other times the first process will not get the input stream and the program will hang. What is the problem?

durron597
  • 31,968
  • 17
  • 99
  • 158
WinterStar
  • 13
  • 3
  • Is the problem that the second process prints `"done"` before the first process reads it, or that the first process gets the `inputStream` before it exists? – durron597 Jul 24 '15 at 21:53
  • I believe it's the latter. I am unfamiliar with how to handle this in Java. The first process is supposed to wait for the string from the second process, though I am unsure of how synchronization should work in this case. – WinterStar Jul 25 '15 at 01:05

1 Answers1

0

I see two options:

  1. Put a Thread.sleep(1000) in front of the print statement to guarantee you've polled the InputStream late enough.
  2. Have the subprocess write to a file (with ProcessBuilder.redirectOutput(File), and then call .readLine() on the file, which will guarantee that you are not late. I would probably delete the temp file before calling ProcessBuilder.start().

Also I would probably not ever call Thread.sleep(Integer.MAX_VALUE) for any reason.

durron597
  • 31,968
  • 17
  • 99
  • 158