Receiving values every second from Linux utilities in a Java program -
i want receive in java output linux command line program. need read values line line, because utilities reporting values 1 time per sec , java programme should not need wait until end of execution. should receive values every second. next little programme works fine in case of ping
command, not perf stat
command.
import java.io.bufferedreader; import java.io.inputstreamreader; import java.io.ioexception; public class main { process p; bufferedreader reader; public main(int number) throws ioexception { if (number == 1) { // not work, blocks on readline() p = runtime.getruntime().exec("sudo perf stat -e cycles -i 1000 -p 9264"); // alter pid 1 monitored } else if (number == 2) { // works! p = runtime.getruntime().exec("ping www.google.com"); } else { system.out.println("either 1 or 2..."); system.exit(0); } reader = new bufferedreader(new inputstreamreader(p.getinputstream())); } public void process() throws ioexception { string res = ""; res = reader.readline(); system.out.println(res); } public static void main (string[] args) throws ioexception, interruptedexception { main mymain = new main(integer.parseint(args[0])); while (true) { mymain.process(); thread.sleep(1000); } } }
so when running java main 2
works correctly, when invoking java main 1
block on reader.readline()
call.
what's difference between 2 commands? command 'ls -l' works correctly , receive values line line.
edit: command works fine, when run straight command line. -i alternative introduced in newer kernel versions, did not exist before (i using kernel 3.11, ubuntu).
when using 2>$1 stderr, indeed read value every second, read null.
the problem seems perf stat not utilize stdout default, stderr. see log-fd option.
so can either redirect stderr stdout in command use,
or capture input stream stderr of process
java linux shell
No comments:
Post a Comment