在Java中创建命名管道

在Java中创建命名管道,java,linux,named-pipes,Java,Linux,Named Pipes,我正在尝试使用Java创建命名管道。我正在使用Linux。然而,我遇到了一个问题,写管道挂起 File fifo = fifoCreator.createFifoPipe("fifo"); String[] command = new String[] {"cat", fifo.getAbsolutePath()}; process = Runtime.getRuntime().exec(command); FileWriter fw = new FileWri

我正在尝试使用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());
第五步执行器:

@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”

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

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

process = Runtime.getRuntime().exec(command);
为此:

process = new ProcessBuilder(command).inheritIO().start();
Runtime.exec已过时。改用ProcessBuilder

更新:

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

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

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

这是可行的。但是,如何获得流程的输出?在此之前,我使用的是process.getInputStream()。如果您知道将使用process.getInputStream()读取输出,则可以选择仅重定向进程的输入。相应地更新了答案。