5

According to:

Java IO implementation of unix/linux "tail -f"

Java "tail -f" wrapper

I assume its possible but I have the following problem.

String TailCommand = "tail -f /path/PATH.txt| grep (...)";
Runtime r = Runtime.getRuntime();
Process p = r.exec(TailCommand);

//handle buffer

while (running) {
    // handle output
}

Process p terminates. It works fine with commands that doesnt have constant updates unlike "top" or "tail -f".

I wonder if I missed something, there is some buffer limitations or whatever? Im using eclipse but i guess that should not have any impact on process behavior.

In fact maybe there is another simply way to solve my issue that i missed. Im using "tail -f" since i have to analyze quite fat(some GBs) log thats constantly appending and dont intend to open it and read the whole file. I need only to controll the appending lines. However i found no suitable tail implementation

Thanks in advance.

Community
  • 1
  • 1

1 Answers1

3

You can't execute piped commands from inside java.

If you want piped output, execute '/bin/sh' like this:

String tailCommand = "/bin/sh -c 'tail -f /path/PATH.txt| grep (...)'";

Also, your java program must consume the output of the process fast enough, so its buffers do not overflow.

You may want to read this article When Runtime.exec() won't, for description of common pitfalls when trying to execute a process from Java.

Alexander Pogrebnyak
  • 44,836
  • 10
  • 105
  • 121
  • 1
    +1 - though, the pipeline won't "overflow". Rather, if your Java app doesn't read the output fast enough, the external command(s) will stall at the point they are writing to their respective output pipes. – Stephen C Feb 11 '13 at 22:56
  • Thanks, it works. At least partially... Piping works well with commands that doesnt update. For example: "tail FILE | grep whatever" - works, "tail -f FILE" (without piping)- works, "tail -f FILE | grep whatever" - no data(process is not dying). – Abecede Abecede Feb 13 '13 at 16:21
  • Hey @AbecedeAbecede, have you solved the problem about "tail -f test.log | grep abc"? I am stucking in it - could not get any output from this kind of command – Alexis Jul 09 '15 at 10:12
  • is there any update to this since there has been some updates to the JDK so far ? – kinsley kajiva Aug 08 '22 at 08:56