Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/linux/25.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在Java程序中每秒从Linux实用程序接收值_Java_Linux_Shell - Fatal编程技术网

在Java程序中每秒从Linux实用程序接收值

在Java程序中每秒从Linux实用程序接收值,java,linux,shell,Java,Linux,Shell,我想用Java接收Linux命令行程序的输出。我需要逐行读取这些值,因为实用程序每秒报告一次它们的值,Java程序不需要等到执行结束。它应该每秒接收一次值。 以下小程序在执行ping命令的情况下工作正常,但在执行perf stat命令的情况下工作不正常 import java.io.BufferedReader; import java.io.InputStreamReader; import java.io.IOException; public class Main { Process

我想用Java接收Linux命令行程序的输出。我需要逐行读取这些值,因为实用程序每秒报告一次它们的值,Java程序不需要等到执行结束。它应该每秒接收一次值。 以下小程序在执行
ping
命令的情况下工作正常,但在执行
perf stat
命令的情况下工作不正常

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) {
        // does NOT work, blocks on readLine()
        p = Runtime.getRuntime().exec("sudo perf stat -e cycles -I 1000 -p 9264"); // change PID to the one to be 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);
        }
}
}
因此,当运行
Javamain2
时,它工作正常,但当调用
Javamain1
时,它将阻塞
reader.readLine()
调用

这两个命令有什么区别?另外,使用命令“ls-l”,它可以正常工作,我可以逐行接收值

编辑: 当我直接从命令行运行命令时,命令本身工作正常。I选项是在较新的内核版本中引入的,它以前不存在(我使用的是内核3.11,Ubuntu)


当使用2>$1同时获取stderr时,它确实会每秒读取一个值,但总是读取null。

问题似乎是perf stat默认情况下不使用stdout,而是使用stderr

所以你可以在你使用的命令中


或者您从

捕获输入流,我怀疑sudo是个问题,我在perf手册页中找不到任何
-I
选项。。。您使用的perf发行版和版本是什么?您确定可以从shell成功运行该命令吗?请阅读stderr,而不仅仅是stdout。它会告诉你出了什么问题。我添加了一些更多的信息来处理这些注释。因为readLine()阻塞了,所以你不需要sleep()。