简体   繁体   English

在Linux中的Java中运行CPU利用率命令

[英]Running CPU Utilization command in Java in Linux

I am writing a Java program which will be run in a Linux machine. 我正在编写将在Linux机器上运行的Java程序。 I wanted to get the CPU utilization of the system. 我想获得系统的CPU利用率。 For getting the cpu utilization of the machine I use the command : 为了获得计算机的cpu利用率,我使用以下命令:

top -bn 2 -d 0.01 | grep '^Cpu.s.' | tail -n 1 | gawk '{print $2+$4+$6}'

Then I call this command from the java code, but I do not get any output. 然后,我从Java代码中调用了此命令,但没有得到任何输出。 Normal linux commands such as ls works for me. ls这样的普通linux命令对我ls

My code is: 我的代码是:

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) {}
     }
}

To use pipes, you need run your command from within a shell: 要使用管道,您需要在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();

Also, please be aware that your command fails on a different locale. 另外,请注意,您的命令在其他区域设置上会失败。 And the output of top may vary too. 而且top的输出也可能有所不同。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM