获取一般linux系统的系统信息,java获取单个进程的CPU使用率

[quote]
一般linux系统内用这些命令获取系统信息:




----------------------------------------------
获取单个进程CPU,内存的占用率

cmd脚本命令:top -b -n 1 -p $pid | sed '$d' | sed -n '$p'
上面的$pid,就是进程的PID

[/quote]

/**
* 获取当前进程的CPU占有率
* cmd:top -b -n 1 -p $pid | sed '$d' | sed -n '$p' | awk '{print $9}'
* @Title: getProcCpu
* @Description: TODO
* @author:zjz
* @create-date:2012-7-16 下午6:22:53
* @modify-date:2012-7-16 下午6:22:53
* @param @param pid
* @param @return
* @return double
* @throws
*
*/
public double getProcCpu(int pid){
Process process=null;
BufferedReader br = null;
try {
if("".equals(procCpuShell))return 0;
procCpuShell = procCpuShell.replaceAll("\\$pid", pid+"");
String[] cmd = new String[]{"/bin/sh","-c",procCpuShell};
process = Runtime.getRuntime().exec(cmd);
int resultCode = process.waitFor();
LogCvt.debug("执行结果PID:"+pid+":"+resultCode);
br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
while((line = br.readLine())!=null ){
Double cpu = Double.parseDouble(line);
if(cpu>100)cpu = cpu/10;//刚启动会出现CPU100多情况,则处理除于10
return cpu;
}
} catch (Exception e) {
LogCvt.error("执行获取进程CPU使用率错误",e);
}finally{
try{
if(process!=null)process.destroy();
if(br!=null)br.close();
}catch(Exception e){
LogCvt.error(e.getMessage());
}

}
return 0.0;
}


如果要获取单个进程使用的内存可以这样:

int mb = 1024*1024;
// 可使用内存
long totalMemory = Runtime.getRuntime().totalMemory() / mb;
// 剩余内存
long freeMemory = Runtime.getRuntime().freeMemory() / mb;
// 最大可使用内存
long maxMemory =Runtime.getRuntime().maxMemory() / mb;

你可能感兴趣的:(linux)