在Java中创建命名管道
发布时间:2020-12-15 04:28:31 所属栏目:Java 来源:网络整理
导读:我正在尝试使用 Java创建命名管道.我正在使用 Linux.但是,我遇到了写入管道的问题. File fifo = fifoCreator.createFifoPipe("fifo"); String[] command = new String[] {"cat",fifo.getAbsolutePath()}; process = Runtime.getRuntime().exec(command); Fil
我正在尝试使用
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”. 解决方法
外部流程具有您需要处理的输入和输出.否则,它们可能会挂起,但它们挂起的确切位置会有所不同.
解决问题的最简单方法是更改??每次出现的问题: process = Runtime.getRuntime().exec(command); 对此: process = new ProcessBuilder(command).inheritIO().start(); Runtime.exec已过时.请改用ProcessBuilder. 更新: inheritIO() is shorthand用于将Process的所有输入和输出重定向到父Java进程的输入和输出.您可以改为仅重定向输入,并自己读取输出: process = new ProcessBuilder(command).redirectInput( ProcessBuilder.Redirect.INHERIT).start(); 然后,您需要从process.getInputStream()中读取进程的输出. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |