process.waitFor(timeout,timeUnit)无法按预期工作

时间:2017-04-04 15:09:00

标签: java java-8 processbuilder

我正在使用ProcessBuilder运行一个进程。 这是相关的代码:

 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();

差异是90秒,但是我不应该在15秒后收到有关失败的错误消息吗?

注意: 我使用stdin为进程提供输入,并将输出和错误流作为字节数组读取。

1 个答案:

答案 0 :(得分:3)

正如user1676075所述,您copy方法一直运行,直到您的流程完成其输出,因此您在流程完成之前从未到达process.waitFor因此永远不会达到waitFor返回的情况不完整的流程代码。