![](/img/trans.png)
[英]Getting the CPU Utilization metric of running aws instance through java client
[英]Running CPU Utilization command in Java in Linux
我正在编写将在Linux机器上运行的Java程序。 我想获得系统的CPU利用率。 为了获得计算机的cpu利用率,我使用以下命令:
top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'
然后,我从Java代码中调用了此命令,但没有得到任何输出。 像ls
这样的普通linux命令对我ls
。
我的代码是:
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) {}
}
}
要使用管道,您需要在shell中运行命令:
ProcessBuilder b = new ProcessBuilder("/bin/sh", "-c",
"top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'");
p = b.start();
另外,请注意,您的命令在其他区域设置上会失败。 而且top
的输出也可能有所不同。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.