注意:
1.如果pro.waitFor()返回1,j即使根据java文档,是operation not permited,但其实基本就是写的shell命令有问题,有时候在linux上可以执行,但放到了java shell中还不是不能执行,比如top命令,要多加个-b才能执行。
2.有时候对于不太活跃的进程进行top命令,会经常得到CPU使用率0,其实可以多次top后再平均。
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.math.BigDecimal;
public class SystemInfoUtil {
public static void getCurrentProcessInfo_linux()
{
//获取当前进程id
String jvmName = ManagementFactory.getRuntimeMXBean().getName();
String pid = jvmName.split("@")[0];
int monitorcount = 4;
String cmd = "top -b -d 5 -p "+pid+" -n "+monitorcount+"|grep java|awk '{print $9\" \"$6}'";
String[] cmds = new String[] { "/bin/sh", "-c", cmd };
InputStream in=null;
BufferedReader read=null;
try
{
Process pro = Runtime.getRuntime().exec(cmds);
if(pro.waitFor()==0)
{
in = pro.getInputStream();
read = new BufferedReader(new InputStreamReader(in));
String line;
double cpu = 0.0;
long mem = 0l;
while((line = read.readLine())!=null)
{
//拿第二行
String cpu_str = line.split(" ")[0];
cpu = cpu+Double.parseDouble(cpu_str);
String mem_str = line.split(" ")[1];
if(mem_str.toLowerCase().contains("g"))
{
mem = mem+Long.parseLong(mem_str.replace("g", ""))*1024*1024;
}
else if(mem_str.toLowerCase().contains("m"))
{
mem = mem+Long.parseLong(mem_str.replace("m", ""))*1024;
}
else
{
mem = mem+Long.parseLong(mem_str);
}
}
cpu = cpu/monitorcount;
mem = mem/monitorcount;
BigDecimal b = new BigDecimal(cpu);
cpu = b.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
}
}
catch (Exception e)
{
e.printStackTrace();
}
}
}