尝试关闭 ProcessBuilder OutputStream 时 Java 挂起

标签 java process

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

一些相关问题似乎与我遇到的相同问题很接近,但我无法弄清楚如何将答案应用于我的问题,因为我是 Java 的相对新手。这是代码。你可以看到我已经输入了很多 println 语句来尝试隔离问题。

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

这是执行此 block 时的输出:

GenMic 正在尝试获取输入文件

GenMic 准备将输入文件写入 out

GenMic 写完出来

最佳答案

当这种情况发生在我身上时,是因为我没有从进程写入的流中读取所有内容。

java.lang.Process 类的 API 文档说:

The created subprocess does not have its own terminal or console. All its standard io (i.e. stdin, stdout, stderr) operations will be redirected to the parent process through three streams (getOutputStream(), getInputStream(), getErrorStream()). The parent process uses these streams to feed input to and get output from the subprocess. Because some native platforms only provide limited buffer size for standard input and output streams, failure to promptly write the input stream or read the output stream of the subprocess may cause the subprocess to block, and even deadlock.



我会尝试在 Process 实例上调用 getInputStream() 并编写一个循环来一次读取一个字节,直到它到达 EOF。而且我会用 getErrorStream() 做同样的事情,以防进程写入标准错误。

关于尝试关闭 ProcessBuilder OutputStream 时 Java 挂起,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2783190/

相关文章:

java - 使用 Android App 在 Raspberry Pi 上执行 SSH 命令

javascript - 访问 scriptlet 内的 Java Map

java - 从表中读取数据时出现问题

c# - 使用 C# 在两个或多个进程之间共享 int 值?

c# - .NET Process.Start() 在远程系统上的可执行文件上 - 安全警告?

node.js - 如何列出脚本中分离的进程?

java - 如何将 html 注释添加到 jsoup 注释中

java - 如何为我的整个框架或对话框使用字体样式?

c - 操作系统、C 和进程内存分配

python - 从另一个 python 脚本终止一个 python 脚本