Saturday, October 24, 2020

Incompatibility of Process.waitFor() between Linux, and Windows.

 

Today, after maybe two years, I figured out, why one particular piece of code works excellent on Windows, but has been causing a lot of trouble on Linux. That piece of code is the class Executor in my Java application framework library afw.


The reason turned out to be, that the method Process.waitFor() behaves differently on Windows, and Linux, with regard to the launched processes output.


  • On Windows, the waitFor() method waits, until
    1. the launched process has terminated, and
    2. the processes standard output, and error output has been consumed (in other words: The input streams, as returned by Process.getInputStream(), and Process.getErrorStream() have been read.
This behaviour can have the unexpected result, that the waitFor() method never returns, which can easily be dealt with by simply launching two separate threads, that read those input streams.
 
  • On Linux, however
    1. The method waits, again, until the launched process has terminated, but
    2. It doesn't wait for the consumption of the processes output.
 
In other words: If you are interested in the processes output, then it is not sufficient, to invoke Process.waitFor(), because the expected output may arrive later on. Instead, you need to launch the same two threads, and then wait, until
  1. both threads have received EOF from their respective input streams, and
  2. the invocation of Process.waitFor() has returned.
That's a bit tricky, indeed.
 
In summary: Java is a highly portable platform. That being said, there might still be issues. Glad, that I could clarify this one.