How to display system's CPU and total ram usage?
I wan't to display CPU usage in percentage and RAM usage in percentage using java 1.4 code. I searched in google its provide some code related to OperatingSystemMXBean
. But it is not supported in java 1.4 version. So Kindly send me the code for this using j开发者_开发问答ava 1.4.
First, I'd recommend you to go toward java 6. It supports everything.
But if not you have no pure java solution. There are 2 others:
- use JNI. In this case you have to write code for each supported platform and compile it on that platform.
- Run external script that does it. use ps for unix: ps -eo pid,ppid,pcpu,vsize,fname,cmd
write WMI script (in JScript or VBScript) on your choice.
This is the script for windows. It prints data using the same format as unix ps command.
var objWMIService = GetObject("winmgmts:\\\\" + "." + "\\root\\CIMV2");
// get CPU usage per process
var pid2cpu = new Object();
var enumItems = new Enumerator(objWMIService.ExecQuery("SELECT IDProcess, PercentProcessorTime FROM Win32_PerfFormattedData_PerfProc_Process"));
for (; !enumItems.atEnd(); enumItems.moveNext()) {
var p = enumItems.item();
pid2cpu[p.IDProcess] = p.PercentProcessorTime;
}
//get process info
enumItems = new Enumerator(objWMIService.ExecQuery("SELECT * FROM Win32_Process"));
for (; !enumItems.atEnd(); enumItems.moveNext()) {
var p = enumItems.item();
var cmd = p.CommandLine==null ? p.Name : p.CommandLine;
var cpu = pid2cpu[p.ProcessID];
WScript.echo(p.ProcessID + " " + p.ParentProcessID + " " + cpu + " " + (p.VirtualSize / 1024) + " " + p.Name + " " + cmd);
}
Save it into file proclist.js and run it as
cscript proclist.js
I have also java wrapper that decide which command to run, reads the command output and parses it but format of this site does not allow to put so big attachments. This code will be available soon through my blog,
so you can either subscribe to blog or write me from blog and I will send you this code shortly.
精彩评论