我正在使用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”。