【发布时间】:2015-04-25 00:20:28
【问题描述】:
我正在编写一个将在 Linux 机器上运行的 Java 程序。我想获得系统的 CPU 利用率。为了获取机器的 cpu 利用率,我使用以下命令:
top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'
然后我从 java 代码调用这个命令,但我没有得到任何输出。像ls 这样的普通 linux 命令对我有用。
我的代码是:
public class HelloWorld{
public static void main(String []args){
String s;
Process p;
try {
p = Runtime.getRuntime().exec("top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'");
BufferedReader br = new BufferedReader(
new InputStreamReader(p.getInputStream()));
while ((s = br.readLine()) != null)
System.out.println("line: " + s);
p.waitFor();
System.out.println ("exit: " + p.exitValue());
p.destroy();
} catch (Exception e) {}
}
}
【问题讨论】: