java 使用shell top命令查看指定进程CPU和内存使用情况

注意:
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();
        }
	}
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值