如果管道中的下一个进程停止,则停止程序
当我运行以下管道时:
cat my_large_file.txt | head | wc
该过程几乎立即停止。好的。
但是当我运行 java 程序时,
java MyProgramReadALargeFile my_large_file.txt | head | wc
“wc”的输出被打印到 stdout
,但 java 程序仍在运行。它如何检测管道已关闭?
谢谢,
when I'm running the following pipeline:
cat my_large_file.txt | head | wc
the process stops almost immediately. OK.
but when I run my java program
java MyProgramReadALargeFile my_large_file.txt | head | wc
the output from 'wc' is printed to stdout
but the java program is still running. How can it detects that the pipeline was closed ?
Thanks,
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
大多数 UNIX 实用程序都会关注 SIGPIPE,它在收到时表示管道流正在写入的进程在另一端没有任何监听,因此无需继续工作。
搜索“java posix Signals”之类的内容会产生一些库,这些库可能允许您将信号处理程序添加到 Java 代码中。
Most UNIX utilities pay attention to SIGPIPE, which, when received, indicates that a piped stream to which the process is writing has nothing listening on the other end, so there's no need to keep working.
Searching for something like "java posix signals" yields some libraries that might allow you to add signal handlers to your Java code.
'head' 在前 10 行后关闭流,因此当 'head' 和 'wc' 完成时 Java 仍在运行是正常的。也许您可以在 Java 代码中测试 System.out 是否仍然打开,但我怀疑这是一个可靠的方法。它可能取决于管道的操作系统实现和 System.out 的 JVM 实现(它是否真正关闭流或只是将其传递到 /dev/null)。
(您是否尝试过cat'ing一个足够大的文件并检查'cat'进程是否在'head'完成后继续运行?)
'head' closes the stream after the first 10 lines, so it is normal that Java is still running while 'head' and 'wc' finished. Perhaps you can test in your Java code if System.out is still open, but I doubt this is a reliable method. It probably depends on the OS implementation of pipes and the JVM implementation of System.out (does it really close the stream or just passes it to /dev/null).
(have you tried cat'ing a file that is large enough and checking if the 'cat' process also keeps on running after 'head' is done?)
我怀疑它从 java prog 的角度关闭了 System.out 。它可能会重定向到/dev/null,但让 head 更容易停止监听 java 程序的输出流,即 exit()。
您可以查看“cat”的源代码,看看它是否对输出流的状态进行任何检测。如果是这种情况,您必须将类似的代码放入“MyProgramReadALargeFile”程序中。否则,头部可能正在做一些输送管道的过程无法检测到的事情。
如果“猫”示例完成的速度值得怀疑,请尝试执行
并查看是否同样快。
I doubt it closes System.out from the perspective of the java prog. It might redirect to /dev/null but would be easier for head to stop listening to the java program's output stream, i.e. exit().
You could look at the source for 'cat' to see if it does any detection on the state of the output stream. If that's the case, you'd have to put similar code in your 'MyProgramReadALargeFile' program. Otherwise head might be doing something the process feeding the pipe can't detect.
If the speed at which the 'cat' example finishes is suspicious, try doing
and see if its just as fast.