【问题标题】:Creating named pipes in Java在 Java 中创建命名管道
【发布时间】:2015-06-29 14:54:55
【问题描述】:

我正在尝试使用 Java 创建命名管道。我正在使用 Linux。但是,我遇到了写入管道挂起的问题。

    File fifo = fifoCreator.createFifoPipe("fifo");
    String[] command = new String[] {"cat", fifo.getAbsolutePath()};
    process = Runtime.getRuntime().exec(command);

    FileWriter fw = new FileWriter(fifo.getAbsoluteFile());
    BufferedWriter bw = new BufferedWriter(fw);
    bw.write(boxString); //hangs here
    bw.close();
    process.waitFor();
    fifoCreator.removeFifoPipe(fifo.toString());

fifoCreator:

@Override
public File createFifoPipe(String fifoName) throws IOException, InterruptedException {
    Path fifoPath = propertiesManager.getTmpFilePath(fifoName);
    Process process = null;
    String[] command = new String[] {"mkfifo", fifoPath.toString()};
    process = Runtime.getRuntime().exec(command);
    process.waitFor();
    return new File(fifoPath.toString());
}

@Override
public File getFifoPipe(String fifoName) {
    Path fifoPath = propertiesManager.getTmpFilePath(fifoName);
    return new File(fifoPath.toString());
}

@Override
public void removeFifoPipe(String fifoName) throws IOException {
    Files.delete(propertiesManager.getTmpFilePath(fifoName));
}

我正在编写一个包含 1000 行的字符串。写 100 行有效,但 1000 行无效。

但是,如果我在外部 shell 上运行“cat fifo”,那么程序会继续并写出所有内容而不会挂起。奇怪的是这个程序启动的cat子进程不起作用。

编辑:我对子进程进行了 ps,它的状态为“S”。

【问题讨论】:

    标签: java linux named-pipes


    【解决方案1】:

    外部流程具有您需要处理的输入和输出。否则,它们可能会挂起,尽管它们挂起的确切点会有所不同。

    解决问题的最简单方法是更改​​每次出现的情况:

    process = Runtime.getRuntime().exec(command);
    

    到这里:

    process = new ProcessBuilder(command).inheritIO().start();
    

    Runtime.exec 已过时。请改用 ProcessBuilder。

    更新:

    inheritIO() is shorthand 用于将所有进程的输入和输出重定向到父 Java 进程的输入和输出。您可以只重定向输入,然后自己读取输出:

    process = new ProcessBuilder(command).redirectInput(
        ProcessBuilder.Redirect.INHERIT).start();
    

    然后你需要从 process.getInputStream() 读取进程的输出。

    【讨论】:

    • 这行得通。但是,我如何获得该过程的输出?在此之前,我使用的是 process.getInputStream()。
    • 如果您知道您将使用 process.getInputStream() 读取输出,您可以选择仅重定向进程的输入。相应地更新了答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-29
    • 1970-01-01
    • 2011-02-13
    • 2014-12-21
    • 2018-10-03
    • 1970-01-01
    相关资源
    最近更新 更多