Java实现 利用sigar.jar监控检测cpu、磁盘、内存的性能值查询和使用量查询 。以及根据进程名查询PID,根据PID杀死进程
import com.sun.jna.Library;
import com.sun.jna.Native;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;
import java.lang.reflect.Field;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import com.sun.jna.Platform;
import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Swap;
import org.springframework.util.StringUtils;
public class GetInfo {
public interface Kernel32 extends Library {
public static Kernel32 INSTANCE = (Kernel32) Native.loadLibrary("kernel32", Kernel32.class);
public long GetProcessId(Long hProcess);
}
public static void getCpuInfo() {
System.out.println("***********获取cpu信息***********");
Sigar sigar = new Sigar();
CpuInfo infos[];
try {
System.out.println("核心cpu数:" + Runtime.getRuntime().availableProcessors());
int cpuLength = sigar.getCpuInfoList().length;
System.out.println("CPU数量" + cpuLength);
infos = sigar.getCpuInfoList();
for (int i = 0; i < infos.length; i++) {
CpuInfo info = infos[i];
System.out.println("第" + i + 1 + "块");
System.out.println("CPU的总量MHzmhz=" + info.getMhz());
System.out.println("获得CPU的卖主,如:Intelvendor=" + info.getVendor());
System.out.println("获得CPU的类别,如:Celeronmodel=" + info.getModel());
System.out.println("缓冲存储器数量cache size=" + info.getCacheSize());
}
} catch (SigarException e1) {
e1.printStackTrace();
}
CpuPerc cpuList[] = null;
try {
cpuList = sigar.getCpuPercList();
} catch (SigarException e) {
e.printStackTrace();
}
for (int i = 0; i < cpuList.length; i++) {
getCpuUsage(cpuList[i], i);
}
}
public static void getCpuUsage(CpuPerc cpu, int i) {
System.out.println("***********获取cpu【" + (i + 1) + "】使用率***********");
System.out.println("CPU用户使用率: " + CpuPerc.format(cpu.getUser()));
System.out.println("CPU系统使用率: " + CpuPerc.format(cpu.getSys()));
System.out.println("CPU当前等待率: " + CpuPerc.format(cpu.getWait()));
System.out.println("CPU当前错误率: " + CpuPerc.format(cpu.getNice()));
System.out.println("CPU当前空闲率: " + CpuPerc.format(cpu.getIdle()));
System.out.println("CPU总的使用率: " + CpuPerc.format(cpu.getCombined()));
}
public static void getDiskInfo() throws SigarException {
System.out.println("***********获取磁盘信息***********");
Sigar sigar = new Sigar();
FileSystem fslist[] = sigar.getFileSystemList();
String dir = System.getProperty("user.home");
System.out.println(dir + " " + fslist.length);
for (int i = 0; i < fslist.length; i++) {
System.out.println("\n~~~~~~~~~~" + i + "~~~~~~~~~~");
FileSystem fs = fslist[i];
System.out.println("分区的盘符名称fs.getDevName() = " + fs.getDevName());
System.out.println("分区的盘符名称fs.getDirName() = " + fs.getDirName());
System.out.println("fs.getFlags() = " + fs.getFlags());
System.out.println("文件系统类型,比如 FAT32、NTFSfs.getSysTypeName() = " + fs.getSysTypeName());
System.out.println("文件系统类型名,比如本地硬盘、光驱、网络文件系统等fs.getTypeName() = " + fs.getTypeName());
System.out.println("文件系统类型fs.getType() = " + fs.getType());
}
}
public static void getDiskUsage() throws SigarException {
System.out.println("***********获取磁盘使用量***********");
Sigar sigar = new Sigar();
FileSystem fslist[] = sigar.getFileSystemList();
for (int i = 0; i < fslist.length; i++) {
System.out.println("\n~~~~~~~~~~" + i + "~~~~~~~~~~");
FileSystem fs = fslist[i];
FileSystemUsage usage = null;
try {
usage = sigar.getFileSystemUsage(fs.getDirName());
} catch (SigarException e) {
if (fs.getType() == 2)
throw e;
continue;
}
switch (fs.getType()) {
case 0:
break;
case 1:
break;
case 2:
System.out.println(" 文件系统总大小Total = " + usage.getTotal() + "KB");
System.out.println(" 文件系统剩余大小Free = " + usage.getFree() + "KB");
System.out.println(" 文件系统可用大小Avail = " + usage.getAvail() + "KB");
System.out.println(" 文件系统已经使用量Used = " + usage.getUsed() + "KB");
double usePercent = usage.getUsePercent() * 100D;
System.out.println(" 文件系统资源的利用率Usage = " + usePercent + "%");
break;
case 3:// TYPE_NETWORK :网络
break;
case 4:// TYPE_RAM_DISK :闪存
break;
case 5:// TYPE_CDROM :光驱
break;
case 6:// TYPE_SWAP :页面交换
break;
}
System.out.println(" DiskReads = " + usage.getDiskReads());
System.out.println(" DiskWrites = " + usage.getDiskWrites());
}
}
public static void getMemoryInfo() throws SigarException {
System.out.println("***********获取内存信息***********");
Sigar sigar = new Sigar();
Mem mem = sigar.getMem();
System.out.println("内存总量Total = " + mem.getTotal() / 1024L / 1024 + "M av");
System.out.println("当前内存使用量Used = " + mem.getUsed() / 1024L / 1024 + "M used");
System.out.println("当前内存剩余量Free = " + mem.getFree() / 1024L / 1024 + "M free");
Swap swap = sigar.getSwap();
System.out.println("交换区总量Total = " + swap.getTotal() / 1024L + "K av");
System.out.println("当前交换区使用量Used = " + swap.getUsed() / 1024L + "K used");
System.out.println("当前交换区剩余量Free = " + swap.getFree() / 1024L + "K free");
}
public static ServerSystemInfoVO setServerSystemInfoVO(ServerSystemInfoVO svo) throws SigarException {
Sigar sigar = new Sigar();
Mem mem = sigar.getMem();
FileSystem fslist[] = sigar.getFileSystemList();
long diskTotal = 0;
for (int i = 0; i < fslist.length; i++) {
FileSystem fs = fslist[i];
FileSystemUsage usage = null;
try {
usage = sigar.getFileSystemUsage(fs.getDirName());
if (fs.getType() == 2) {
diskTotal += usage.getTotal() * 1024;
}
String host = System.getProperty("java.rmi.server.hostname");
svo.setIp((host == null || host.length() == 0) ? InetAddress.getLocalHost().getHostAddress() : host);
svo.setCpuCoreCount(Runtime.getRuntime().availableProcessors());
svo.setCpuCount(sigar.getCpuInfoList().length);
svo.setDiskTotal(diskTotal);
svo.setMemoryTotal(mem.getTotal());
} catch (SigarException e) {
if (fs.getType() == 2)
throw e;
continue;
} catch (UnknownHostException e) {
e.printStackTrace();
}
}
return svo;
}
public static ServerResourceVO setServerResourceVO(ServerResourceVO svo) {
Sigar sigar = new Sigar();
float cpuLoad = 0;
try {
Mem mem = sigar.getMem();
double cputotal = 0;
double Combinedtotal = 0;
CpuPerc cpuList[] = sigar.getCpuPercList();
for (int i = 0; i < cpuList.length; i++) {
CpuPerc cpu = cpuList[i];
Combinedtotal += cpu.getCombined();
cputotal += 1;
}
cpuLoad = (float) (Combinedtotal / cputotal);
long memoryUsage = mem.getUsed();
FileSystem fslist[] = sigar.getFileSystemList();
long diskUsage = 0;
for (int i = 0; i < fslist.length; i++) {
FileSystem fs = fslist[i];
FileSystemUsage usage = null;
try {
usage = sigar.getFileSystemUsage(fs.getDirName());
if (fs.getType() == 2) {
diskUsage += usage.getUsed() * 1024;
}
} catch (SigarException e) {
if (fs.getType() == 2)
throw e;
continue;
}
}
String host = System.getProperty("java.rmi.server.hostname");
Date date = new Date();
svo.setIp((host == null || host.length() == 0) ? InetAddress.getLocalHost().getHostAddress() : host);
svo.setCpuLoad(cpuLoad);
svo.setDiskUsage(diskUsage);
svo.setMemoryUsage(memoryUsage);
svo.setTimestamp(date.getTime());
} catch (SigarException e1) {
e1.printStackTrace();
} catch (UnknownHostException e) {
e.printStackTrace();
}
return svo;
}
public static void findExecuterProcess(String processName) {
try {
Process process = null;
if (Platform.isWindows()) {
String[] cmmd = { "cmd", "/c",
"FOR /F \"tokens=2,3*\"; %i in ('tasklist /nh ^| find \"" + processName + "\"') do @echo %i" };
process = Runtime.getRuntime().exec(cmmd);
} else if (Platform.isLinux() || Platform.isAIX()) {
String cmmd = "ps -ef | grep \"" + processName + "\" | grep -v grep | awk '{print $2}'";
process = Runtime.getRuntime().exec(cmmd);
}
String str = null;
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
while ((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (IOException e) {
e.printStackTrace();
}
}
public static boolean killProcessByPid(String pid) {
if (StringUtils.isEmpty(pid) || "-1".equals(pid)) {
throw new RuntimeException("Pid ==" + pid);
}
Process process = null;
BufferedReader reader = null;
String command = "";
boolean result = false;
if (Platform.isWindows()) {
command = "cmd.exe /c taskkill /PID " + pid + " /F /T ";
} else if (Platform.isLinux() || Platform.isAIX()) {
command = "kill -9 " + pid;
}
try {
process = Runtime.getRuntime().exec(command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream(), "utf-8"));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println("kill PID return info -----> " + line);
}
result = true;
} catch (Exception e) {
result = false;
} finally {
if (process != null) {
process.destroy();
}
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
}
}
}
return result;
}
public static void main(String[] args) throws SigarException {
findExecuterProcess("Notepad.exe");
}
}