From: http://avery-leo.javaeye.com/blog/298724
Source code:
- Import java. io. BufferedReader;
- Import java. io. File;
- Import java. io. FileInputStream;
- Import java. io. IOException;
- Import java. io. InputStreamReader;
- Import java.net. InetAddress;
- Import java. util. StringTokenizer;
-
- Import org. apache. log4j. Logger;
-
- /**
- * Obtain cpu and memory information in linux
- *
- * <P>
- *
- * @ Author leo
- * </P>
- * @ Date 2008
- */
- Public final class linuxsystemtool implements runnable {
- Private logger log = logger. getlogger (linuxsystemtool. Class );
- Private config Config = config. getinstance ();
- /**
- * Get memory by used info
- *
- * @ Return int [] Result
- * Result. Length = 4; int [0] = memtotal; int [1] = memfree; int [2] = swaptotal; int [3] = swapfree;
- * @ Throws ioexception
- * @ Throws interruptedexception
- */
- Public void run (){
- // TODO Auto-generated method stub
-
- While (true ){
-
- Try {
- Exec ();
- Thread. sleep (config. getThreadTime ());
- } Catch (Exception e ){
- // TODO Auto-generated catch block
- Log. error ("Performance Monitoring error:" + e. getMessage ());
- E. printstacktrace ();
- }
- }
- }
- Public void exec () throws exception {
- // Serverstatus Ss = new serverstatus ();
-
- Inetaddress Inet = inetaddress. getlocalhost ();
- System. Out. println ("performance monitoring IP:" + inet. tostring ());
-
- String IP = inet. tostring (). substring (inet. tostring (). indexof ("/") + 1 );
- Log.info ("performance monitoring IP:" + IP );
-
- Int [] meminfo = linuxsystemtool. getmeminfo ();
- System. Out. println ("memtotal:" + meminfo [0]);
- System. Out. println ("memfree:" + meminfo [1]);
-
- Snmputil util = new snmputil ();
- Util. setcpu (getcpuinfo ());
- // Util. setdisk (1 );
- Util. setmem (meminfo [0]/meminfo [1]);
- Util. setip (IP );
-
- }
- Public static int [] getMemInfo () throws IOException, InterruptedException {
- File file = new File ("/proc/meminfo ");
- BufferedReader br = new BufferedReader (new InputStreamReader (new FileInputStream (file )));
- Int [] result = new int [4];
- String str = null;
- StringTokenizer token = null;
- While (str = br. readLine ())! = Null ){
- Token = new StringTokenizer (str );
- If (! Token. hasMoreTokens ())
- Continue;
-
- Str = token. nextToken ();
- If (! Token. hasMoreTokens ())
- Continue;
-
- If (str. Repeated signorecase ("MemTotal :"))
- Result [0] = Integer. parseInt (token. nextToken ());
- Else if (str. equalsIgnoreCase ("MemFree :"))
- Result [1] = Integer. parseInt (token. nextToken ());
- Else if (str. equalsIgnoreCase ("SwapTotal :"))
- Result [2] = Integer. parseInt (token. nextToken ());
- Else if (str. equalsIgnoreCase ("SwapFree :"))
- Result [3] = Integer. parseInt (token. nextToken ());
- }
-
- Return result;
- }
-
- /**
- * Get memory by used info
- *
- * @ Return float efficiency
- * @ Throws IOException
- * @ Throws InterruptedException
- */
- Public static float getCpuInfo () throws IOException, InterruptedException {
- File file = new File ("/proc/stat ");
- Bufferedreader BR = new bufferedreader (New inputstreamreader (New fileinputstream (File )));
- Stringtokenizer token = new stringtokenizer (Br. Readline ());
- Token. nexttoken ();
- Long user1 = long. parselong (token. nexttoken ());
- Long nice1 = long. parselong (token. nexttoken ());
- Long sys1 = long. parselong (token. nexttoken ());
- Long idle1 = long. parselong (token. nexttoken ());
- Thread. Sleep (1000 );
- BR = new bufferedreader (New inputstreamreader (New fileinputstream (File )));
- Token = new stringtokenizer (Br. Readline ());
- Token. nexttoken ();
- Long user2 = long. parselong (token. nexttoken ());
- Long nice2 = long. parselong (token. nexttoken ());
- Long sys2 = long. parselong (token. nexttoken ());
- Long idle2 = long. parselong (token. nexttoken ());
- Return (float) (user2 + sys2 + nice2)-(user1 + sys1 + nice1 ))
- /(Float) (user2 + nice2 + sys2 + idle2)-(user1 + nice1 + sys1 + idle1 ));
- }
-
- /**
- * Test class
- *
- * <P>
- *
- * @ Author
- * </P>
- * @ Date
- */
-
- Public static void main (String [] args) throws Exception {
- Int [] meminfo = linuxsystemtool. getmeminfo ();
- System. Out. println ("memtotal:" + meminfo [0]);
- System. Out. println ("memfree:" + meminfo [1]);
- System. Out. println ("swaptotal:" + meminfo [2]);
- System. Out. println ("swapfree:" + meminfo [3]);
- System. Out. println ("CPU usage:" + linuxsystemtool. getcpuinfo ());
- }
- }
Note: The original text uses int to save the CPU Count value, which is inappropriate. Conversion Value overflow may occur on servers that run for a long time.
1. CPU
The file "/proc/stat" contains CPU information. Every CPU tick is used in this file. The following numbers indicate user, nice, sys, idle, and iowait. Some versions of kernel do not include iowait. These values indicate where each tick of the CPU is used from the boot to the present. For example:
Cpu0 256279030 0 11832528 1637168262
That is, 256279030 tick is used for user consumption since CPU 0 is started, and 11832528 is used for sys consumption. So if you want to calculate the CPU load per unit time (for example, 1 s), you only need to calculate the difference between the values before and after 1 second by the number of tick per second. Gkrellm is implemented in this way: (200 * (v2-v1)/CPU_TICKS_PER_SECOND) + 1)/2
For example, if you read/proc/stat for the first time, the user value is 256279030; if you read it again after one second, the value is 256289030, the CPU user consumption in this second is: (200 * (256289030-256279030)/CPU_TICKS_PER_SECOND) + 1)/2 = (10000*200/1000000) + 1) /2 = 1%.
2. memory consumption
The file "/proc/meminfo" contains the memory information and swap information. For example:
$ Cat/proc/meminfo
Total: used: free: shared: buffers: cached:
Mem: 1057009664 851668992 205340672 0 67616768 367820800
Swap: 2146787328 164429824 1982357504
MemTotal: 1032236 kB
MemFree: 200528 kB
MemShared: 0 kB
......
However, from the source code of gkrellm, some versions do not have the statistics of the previous two rows, but can only collect data based on the following types of Key: Value.
3. Disk Space
From the source code of gkrellm, this is a very complex data. Disk partition data may be distributed in:/proc/mounts,/proc/diskstats,/proc/partitions, and so on. In addition, if you want to check a specific path, you also need the help of commands such as mount and df. To reduce the trouble, I can directly use the statfs function to obtain this data.
Int statfs (const char * path, struct statfs * buf );
This function only needs to enter the path name to be checked to return the space usage of the partition where the path is located:
Total Space: buf. f_bsize * buf. f_blocks
Free Space: buf. f_bsize * buf. f_bavail
4. Disk I/O
Disk I/O data is also complex. For some versions, see/proc/diskstats, for some versions, see/proc/partitions, and for some versions, I still don't know where to view them ...... However, we can see that the data version is also the same as the CPU, which requires a value every other time. The difference between the two values is the traffic.
5. Network Traffic
Network traffic is also varied, but it can basically be obtained in/proc/net/dev. It also requires two values to take the difference as the traffic value.