尝试关闭ProcessBuilder OutputStream时,Java挂起 [英] Java hangs when trying to close a ProcessBuilder OutputStream

查看:497
本文介绍了尝试关闭ProcessBuilder OutputStream时,Java挂起的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下Java代码来启动ProcessBuilder,打开一个OutputStream,让进程将一个字符串写入一个OutputStream,然后关闭OutputStream。当我尝试关闭OutputStream时,整个事情无限期地挂起。这只发生在Windows上,永远不会发生在Mac或Linux上。

I have the following Java code to start a ProcessBuilder, open an OutputStream, have the process write a string to an OutputStream, and then close the OutputStream. The whole thing hangs indefinitely when I try to close the OutputStream. This only happens on Windows, never on Mac or Linux.

一些相关的问题似乎与我遇到的问题很接近,但我没有能够弄清楚如何应用我的问题的答案,因为我是Java的相对新手。这是代码。你可以看到我已经输入了很多println语句来试图找出问题。

Some of the related questions seem to be close to the same problem I'm having, but I haven't been able to figure out how to apply the answers to my problem, as I am a relative newbie with Java. Here is the code. You can see I have put in a lot of println statements to try to isolate the problem.

    System.out.println("GenMic trying to get the input file now");
    System.out.flush();
    OutputStream out = child.getOutputStream();
    try {
        System.out.println("GenMic getting ready to write the input file to out");
        System.out.flush();
        out.write(intext.getBytes());  // intext is a string previously created
        System.out.println("GenMic finished writing to out");
        System.out.flush();
        out.close();
        System.out.println("GenMic closed OutputStream");
        System.out.flush();
    } catch (IOException iox) {
        System.out.println("GenMic caught IOException 2");
        System.out.flush();
        String detailedMessage = iox.getMessage();
        System.out.println("Exception: " + detailedMessage);
        System.out.flush();
        throw new RuntimeException(iox);
    }

以下是此块执行时的输出:

And here is the output when this chunk is executed:

GenMic试图立即获取输入文件

GenMic trying to get the input file now

GenMic准备将输入文件写出来

GenMic getting ready to write the input file to out

GenMic写完了

推荐答案

你需要确保<$>返回的流c $ c> getInputStream()和 getOutputStream()在各个线程上耗尽,这些线程与关闭流的线程不同由 getOutputStream()返回。

You need to make sure that the streams returned by getInputStream() and getOutputStream() are drained on individual threads and these threads are different from the one on which you close the stream returned by getOutputStream().

基本上要求每个子流程至少有3个线程你想操纵并检查它的 stdin stdout stderr 。根据您的具体情况,其中一个线程可能是您当前的执行线程(您在其上创建ProcessBuilder的线程)。

Basically it is a requirement to have at least 3 threads per sub-process if you want to manipulate and examine its stdin, stdout and stderr. One of the threads, depending on your circumstances, may be your current execution thread ( the one on which you create ProcessBuilder ).

这篇关于尝试关闭ProcessBuilder OutputStream时,Java挂起的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆