Creating named pipes in Java

I'm trying to create named pipes in Java I'm using Linux However, I encountered a problem writing to the pipeline

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(@R_246_2419@String); //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));
}

I'm writing a string of 1000 lines Writing 100 lines is valid, but 1000 lines are not

However, if I run "cat FIFO" on an external shell, the program continues to execute and writes everything without hanging The strange thing is how the cat subprocess started by this program works

Editor: I made a PS on the subprocess, and its status is "s"

Solution

External processes have inputs and outputs that you need to process Otherwise, they may hang, but the exact location where they hang will vary

The easiest way to solve the problem is to change the problem every time:

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

In this regard:

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

Runtime. Exec is out of date Use processbuilder. Instead

to update:

Inheritio() is shorthand is used to redirect all input and output of the process to the input and output of the parent java process Instead, you can redirect the input only and read the output yourself:

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

Then, you need to start from process Getinputstream() reads the output of the process

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>