如何让管道头到头退出java [英] How do I get java to exit when piped to head

查看:137
本文介绍了如何让管道头到头退出java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个java进程打印出很多文本。有时我只想看一点文字。使用正常的程序,我可以做:

  $ myprog |头

我将从myprog看到10行输出,它将立即退出。但是使用java,如果我这样做:

  $ java MyClass |头

我得到前10行输出,但java进程不会退出,直到完成所有的处理。这就像java不关心stdout(System.out)已经消失,头进程已经死了。



所有其他程序可以静默地退出,如猫:

  $ cat / etc / group |头
root:x:0:
守护进程:x:1:
bin:x:2:
sys:x:3:
adm:x:4 :
tty:x:5:
disk:x:6:
lp:x:7:
mail:x:8:
news:x:9 :

或者使用断开的管道错误/异常退出,如python:

  $ python -c'while True:printhi'|头









hi
追溯(最近的最后一次呼叫):
文件< string>,第1行,< module>
IOError:[Errno 32] Broken pipe

如何让java引发异常调用System.out.println()当我输出管道输出到头像?我希望能够执行以下操作:

  try {
while(true){
System.out.println(嗨);
}
} catch(BrokenPipeException e){
//优雅退出
}


解决方案

如果您不喜欢 .checkError() ://stackoverflow.com/questions/11695500/how-do-i-get-java-to-exit-when-piped-to-head/11695708#11695708> Sascha的答案,宁可收到例外可以使用

  OutputStream stream = new FileOutputStream(FileDescriptor.out); 

您失去了 PrintStream 的特定功能。在我的情况下,他们是不相关的,这种方法比建立一堆黑客检查更容易。



请注意,如果您重定向了 System.out 通过 System.setOut ,作为 FileDescriptor.out 将指向原始的输出描述符,而不是您重定向的描述符。


I have a java process which prints out a lot of text. Sometimes I just want to see a bit of the text. With normal programs I can just do:

$ myprog | head

I'll just see 10 lines of output from myprog and it will exit immediately. But with java, if I do:

$ java MyClass | head

I get the first 10 lines of output, but the java process won't exit until it's done with all of its processing. It's like java doesn't care that stdout (System.out) is gone and the head process is dead and gone.

All other programs either exit silently, like cat:

$ cat /etc/group | head
root:x:0:
daemon:x:1:
bin:x:2:
sys:x:3:
adm:x:4:
tty:x:5:
disk:x:6:
lp:x:7:
mail:x:8:
news:x:9:

Or exit with a broken pipe error/exception, like python:

$ python -c 'while True: print "hi"' | head
hi
hi
hi
hi
hi
hi
hi
hi
hi
hi
Traceback (most recent call last):
  File "<string>", line 1, in <module>
IOError: [Errno 32] Broken pipe

How can get java to raise an exception when calling System.out.println() when I pipe output to something like head? I'd love to be able to do something like:

try {
    while(true) {
        System.out.println("hi");
    }
} catch(BrokenPipeException e) {
    // exit gracefully
}

解决方案

If you don't like the .checkError() method from Sascha's answer and would rather receive exceptions you can use

OutputStream stream = new FileOutputStream(FileDescriptor.out);

You lose the PrintStream specific functions. In my case, they weren't relevant and this approach was easier than building a bunch of hacky checks.

Note that this will not behave if you've redirected the System.out via System.setOut, as FileDescriptor.out will point to the original output descriptor, not your redirected one.

这篇关于如何让管道头到头退出java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆