【问题标题】:Java process execute "tail -f test.log | grep abc" can't not get any outputJava进程执行“tail -f test.log | grep abc”不能得到任何输出
【发布时间】:2015-07-09 10:30:36
【问题描述】:

我写了一个java程序来执行linux命令。但我发现它无法从命令“tail -f test.log | grep abc”中获得任何输出

以下是几个例子:

"tail -n 100 test.log | grep abc" -- works
"tail -f test.log" -- works  
"tail -f test.log | grep abc" -- not works

我的 Java 代码

String[] cmd = new String[] {"/bin/sh", "-c", "tail -f /Users/Alexis/Test/test.log | grep abc"};
InputStream inputStream = Runtime.getRuntime().exec(cmd).getInputStream();
byte[] bb = new byte[8];
int i = 0;
while ((i = inputStream.read(bb)) != -1) {
    System.out.println("received : " + new String(bb, Charsets.UTF_8));
}

当我在 test.log 中回显某些内容时,我无法获得任何输出。

【问题讨论】:

  • 由于 tail -f 没有终止,数据可能仍在管道缓冲区中。你可以试试“unbuffer tail -f test.log | grep abc”吗?
  • @ManuelBarbe 我试过但没用 :(
  • 在您的程序运行时,带有abc 的行是否仍被附加到 test.log 中?好像没有,最后 100 行中有 abc 行,但最后 10 行左右没有 - 它会准确解释您所看到的。在终端中手动运行 cmds 时,您是否看到相同的行为?只是试图排除明显的......

标签: java linux bash shell


【解决方案1】:

最后我使用'tail -f test.log | unbuffer -p grep abc' 就可以了

另外,您可以使用 'tail -f test.log | stdbuf -o0 grep abc'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    • 2012-12-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-09
    相关资源
    最近更新 更多