Search code examples
javajava-8processbuilder

process.waitFor(timeout, timeUnit) does not work as expected


I am running a process using ProcessBuilder. This is the relevant code :

 ByteArrayOutputStream resultStream = new ByteArrayOutputStream();
 ByteArrayOutputStream errorMessage = new ByteArrayOutputStream();
 ProcessBuilder pb = null;

 pb = new ProcessBuilder("/usr/local/bin/convert", "-limit", "time", "50", "-", "-resize", maxWidth + "x" + maxHeight+">", "-quality", "82","png:-");

 System.out.println(pb.command());
 long startTime = System.currentTimeMillis();
 System.out.println("start time: " + startTime);
 Process process = pb.start();
 OutputStream stdIn = process.getOutputStream();
 copy(input, stdIn);
 stdIn.flush();
 stdIn.close();
 copy(process.getInputStream(), resultStream);
 copy(process.getErrorStream(), errorMessage);

 boolean exitStatus = process.waitFor(15, TimeUnit.SECONDS);
 if (!exitStatus) {
           System.out.println("Image processing failed with status " + exitStatus + ": " + errorMessage.toString());
 }

        input.close();

        System.out.println("returning");
        long endTime = System.currentTimeMillis();
        System.out.println(endTime);
        System.out.println("difference :" + (endTime - startTime)*1.0/1000 + " seconds");
        return resultStream.toByteArray();

The difference is 90 seconds, but shouldn't i get an the error message regarding failure after 15 secs?

NOTES : I am providing the input to the process using stdin, and reading the output and error streams as byte arrays.


Solution

  • As user1676075 stated, you copy method runs until your process finishes its output, so that you never reached process.waitFor before the process' completion thus never attaining the case where the waitFor returns an incomplete process code.