top、ps命令查看當前cpu、mem使用情況

Linux下提供top、ps命令查看當前cpu、mem使用情況,簡要介紹如下:

一、使用ps查看進程的資源佔用

ps -aux

查看進程信息時,第三列就是CPU佔用。

[root@localhost utx86]# ps -aux | grep my_process
Warning: bad syntax, perhaps a bogus '-'? See /usr/share/doc/procps-3.2.7/FAQ



root 14415 3.4 0.9 37436 20328 pts/12 SL+ 14:18 0:05 ./my_process
root 14464 0.0 0.0 3852 572 pts/3 S+ 14:20 0:00 grep my_process
每一列含義如下

USER PID %CPU %MEM VSZ RSS TTY STAT START TIME COMMAND

即my_process進程當前佔用cpu 3.4%, 內存0.9%

二、top動態查看系統負荷

top -n 1

顯示後退出

[root@localhost utx86]# top -n 1
top - 14:23:20 up 5:14, 14 users, load average: 0.00, 0.04, 0.01
Tasks: 183 total, 1 running, 181 sleeping, 1 stopped, 0 zombie
Cpu(s): 1.8%us, 1.4%sy, 0.0%ni, 95.8%id, 0.7%wa, 0.1%hi, 0.2%si, 0.0%st
Mem: 2066240k total, 1507316k used, 558924k free, 190472k buffers
Swap: 2031608k total, 88k used, 2031520k free, 1087184k cached

1、獲取cpu佔用情況

[root@localhost utx86]# top -n 1 |grep Cpu
Cpu(s): 1.9%us, 1.3%sy, 0.0%ni, 95.9%id, 0.6%wa, 0.1%hi, 0.2%si, 0.0%st

解釋:1.9%us是用戶佔用cpu情況

1.3%sy,是系統佔用cpu情況

得到具體列的值:

[root@localhost utx86]# top -n 1 |grep Cpu | cut -d "," -f 1 | cut -d ":" -f 2
1.9%us
[root@localhost utx86]# top -n 1 |grep Cpu | cut -d "," -f 2
1.3%sy

2、獲得內存佔用情況

[root@localhost utx86]# top -n 1 |grep Mem
Mem: 2066240k total, 1515784k used, 550456k free, 195336k buffers

獲得內存情況指定列

[root@localhost c++_zp]# top -n 1 |grep Mem | cut -d "," -f 1 | cut -d ":" -f 2
2066240k total
[root@localhost c++_zp]# top -n 1 |grep Mem | cut -d "," -f 2
1585676k used

三、編程實現

現在可以通過程序將cpu使用率、內存使用情況保存到文件中

test.cpp


#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
int main()
{
system("top -n 1 |grep Cpu | cut -d \",\" -f 1 | cut -d \":\" -f 2 >cpu.txt");
system("top -n 1 |grep Cpu | cut -d \",\" -f 2 >>cpu.txt");
system("top -n 1 |grep Mem | cut -d \",\" -f 1 | cut -d \":\" -f 2 >>cpu.txt");
system("top -n 1 |grep Mem | cut -d \",\" -f 2 >>cpu.txt");
return 0;
}



編譯、運行:

[root@localhost study]# g++ test.cpp
[root@localhost study]# ./a.out
[root@localhost study]# cat cpu.txt
2.1%us
1.5%sy
2066240k total

1619784k used


四、硬盤使用率編程實現

1.硬盤使用率 命令df -lh

2.程序實現,調用statfs

c:

int statfs(const char *path, struct statfs *buf); 
int fstatfs(int fd, struct statfs *buf); 
struct statfs { 
long f_type; /* type of filesystem (see below) */ 
long f_bsize; /* optimal transfer block size */ 
long f_blocks; /* total data blocks in file system */ 
long f_bfree; /* free blocks in fs */ 
long f_bavail; /* free blocks avail to non-superuser */ 
long f_files; /* total file nodes in file system */ 
long f_ffree; /* free file nodes in fs */ 
fsid_t f_fsid; /* file system id */ 
long f_namelen; /* maximum length of filenames */ 
};


int fstatvfs(int fildes, struct statvfs *buf); 
int statvfs(const char *restrict path, struct statvfs *restrict buf);

struct statvfs { 
unsigned long f_bsize; /* file system block size */ 
unsigned long f_frsize; /* fragment size */ 
fsblkcnt_t f_blocks; /* size of fs in f_frsize units */ 
fsblkcnt_t f_bfree; /* # free blocks */ 
fsblkcnt_t f_bavail; /* # free blocks for non-root */ 
fsfilcnt_t f_files; /* # inodes */ 
fsfilcnt_t f_ffree; /* # free inodes */ 
fsfilcnt_t f_favail; /* # free inodes for non-root */ 
unsigned long f_fsid; /* file system id */ 
unsigned long f_flag; /* mount flags */ 
unsigned long f_namemax; /* maximum filename length */ 
};


#include <sys/vfs.h> 
#include <sys/statvfs.h> 
#include <string.h> 
#include <stdlib.h> 
#include <stdio.h> 
int gethd(char *path); 
int main() 
{ 
char buf[256],*ptr; 
FILE *file; 
while(1) 
{ 
file=fopen("/etc/fstab","r"); 
if(!file)return; 
memset(buf,0,sizeof(buf)); 
while(fgets(buf,sizeof(buf),file)) 
{ 
ptr=strtok(buf," "); 
if(ptr&&((strncmp(ptr,"/dev",4)==0))) 
{ 
ptr=strtok(NULL," "); 
gethd(ptr); 
} 
} 
fclose(file); 
sleep(2); 
} 
}

int gethd(char *path) 
{ 
struct statvfs stat1; 
statvfs(path,&stat1); 
if(stat1.f_flag) 
printf("%s total=%dK free=%dK %0.1f%%

\n",path,stat1.f_bsize*stat1.f_blocks/1024,stat1.f_bsize*stat1.f_bfree/1024,

((float)stat1.f_blocks-(float)stat1.f_bfree)/(float)stat1.f_blocks*100); 
}



java:

import java.io.*; 

/** 
* linux 下cpu 內存 磁盤 jvm的使用監控 
* @author avery_leo 
* 
*/ 
public class TT { 
/** 
* 獲取cpu使用情況 
* @return 
* @throws Exception 
*/ 
public double getCpuUsage() throws Exception { 
double cpuUsed = 0; 

Runtime rt = Runtime.getRuntime(); 
Process p = rt.exec("top -b -n 1");// 調用系統的“top"命令 

BufferedReader in = null; 
try { 
in = new BufferedReader(new InputStreamReader(p.getInputStream())); 
String str = null; 
String[] strArray = null; 

while ((str = in.readLine()) != null) { 
int m = 0; 

if (str.indexOf(" R ") != -1) {// 只分析正在運行的進程,top進程本身除外 && 

strArray = str.split(" "); 
for (String tmp : strArray) { 
if (tmp.trim().length() == 0) 
continue; 
if (++m == 9) {// 第9列爲CPU的使用百分比(RedHat 

cpuUsed += Double.parseDouble(tmp); 

} 

} 

} 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} finally { 
in.close(); 
} 
return cpuUsed; 
} 
/** 
* 內存監控 
* @return 
* @throws Exception 
*/ 
public double getMemUsage() throws Exception { 

double menUsed = 0; 
Runtime rt = Runtime.getRuntime(); 
Process p = rt.exec("top -b -n 1");// 調用系統的“top"命令 

BufferedReader in = null; 
try { 
in = new BufferedReader(new InputStreamReader(p.getInputStream())); 
String str = null; 
String[] strArray = null; 

while ((str = in.readLine()) != null) { 
int m = 0; 

if (str.indexOf(" R ") != -1) {// 只分析正在運行的進程,top進程本身除外 && 
// 
// System.out.println("------------------3-----------------"); 
strArray = str.split(" "); 
for (String tmp : strArray) { 
if (tmp.trim().length() == 0) 
continue; 

if (++m == 10) { 
// 9)--第10列爲mem的使用百分比(RedHat 9) 

menUsed += Double.parseDouble(tmp); 

} 
} 

} 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} finally { 
in.close(); 
} 
return menUsed; 
} 

/** 
* 獲取磁盤空間大小 
* 
* @return 
* @throws Exception 
*/ 
public double getDeskUsage() throws Exception { 
double totalHD = 0; 
double usedHD = 0; 
Runtime rt = Runtime.getRuntime(); 
Process p = rt.exec("df -hl");//df -hl 查看硬盤空間 

BufferedReader in = null; 
try { 
in = new BufferedReader(new InputStreamReader(p.getInputStream())); 
String str = null; 
String[] strArray = null; 
int flag = 0; 
while ((str = in.readLine()) != null) { 
int m = 0; 
// if (flag > 0) { 
// flag++; 
strArray = str.split(" "); 
for (String tmp : strArray) { 
if (tmp.trim().length() == 0) 
continue; 
++m; 
// System.out.println("----tmp----" + tmp); 
if (tmp.indexOf("G") != -1) { 
if (m == 2) { 
// System.out.println("---G----" + tmp); 
if (!tmp.equals("") && !tmp.equals("0")) 
totalHD += Double.parseDouble(tmp 
.substring(0, tmp.length() - 1)) * 1024; 

} 
if (m == 3) { 
// System.out.println("---G----" + tmp); 
if (!tmp.equals("none") && !tmp.equals("0")) 
usedHD += Double.parseDouble(tmp.substring( 
0, tmp.length() - 1)) * 1024; 

} 
} 
if (tmp.indexOf("M") != -1) { 
if (m == 2) { 
// System.out.println("---M---" + tmp); 
if (!tmp.equals("") && !tmp.equals("0")) 
totalHD += Double.parseDouble(tmp 
.substring(0, tmp.length() - 1)); 

} 
if (m == 3) { 
// System.out.println("---M---" + tmp); 
if (!tmp.equals("none") && !tmp.equals("0")) 
usedHD += Double.parseDouble(tmp.substring( 
0, tmp.length() - 1)); 
// System.out.println("----3----" + usedHD); 
} 
} 

} 

// } 
} 
} catch (Exception e) { 
e.printStackTrace(); 
} finally { 
in.close(); 
} 
return (usedHD / totalHD) * 100; 
} 

public static void main(String[] args) throws Exception { 
TT cpu = new TT(); 
System.out.println("---------------cpu used:" + cpu.getCpuUsage() + "%"); 
System.out.println("---------------mem used:" + cpu.getMemUsage() + "%"); 
System.out.println("---------------HD used:" + cpu.getDeskUsage() + "%"); 
System.out.println("------------jvm監控----------------------"); 
Runtime lRuntime = Runtime.getRuntime(); 
System.out.println("--------------Free Momery:" + lRuntime.freeMemory()+"K"); 
System.out.println("--------------Max Momery:" + lRuntime.maxMemory()+"K"); 
System.out.println("--------------Total Momery:" + lRuntime.totalMemory()+"K"); 
System.out.println("---------------Available Processors :" 
+ lRuntime.availableProcessors()); 
} 
}


shell:

監視磁盤hda1

#!/bin/sh
# disk_mon
# monitor the disk space
# get percent column and strip off header row from df
LOOK_OUT=0
until [ "$LOOK_OUT" -gt "90" ]
do
LOOK_OUT=`df | grep /hda1 | awk '{print $5}' | sed 's/%//g'`
echo $LOOK_OUT%
sleep 1
done

echo "Disk hda1 is nearly full!"

hdtest.sh

#!/bin/ksh
#檢測硬盤剩餘空間並警告的shell V050921
#四川省樂山市沙灣區郵政局 宋濤
#精簡代碼,改進增強 V050923

#簡單說明: 可由root用戶將此腳本加入crontab,啓動時間一般最好設爲每天營業前,當此腳本啓動時如檢測到已用硬盤空間超過指定範圍,則將hdwarning.sh腳本拷貝到指定用戶根目錄下;否則將刪除指定用戶的目錄下的hdwarning.sh腳本.

usedhd=80 #自定義超限已用硬盤空間大小比例,默認爲80%
test "$1" && userdir=$1 || userdir=/usr/scabs #前臺用戶的目錄(默認設爲統版用戶),也可在調用此腳本時加上指定前臺用戶的目錄參數

hdwarning=$(df -v |sed '1d;s/.$//;s/\/dev\///'|awk '$6>'"$usedhd"' {print $2," = ",$6"%"}')
test "$hdwarning" && { cp /usr/bin/hdwarning.sh ${userdir}/hdwarning.sh \
> ${userdir}/hdwarning.log  chmod 777 ${userdir}/hdwarning.sh ${userdir}/hdwarning.log } \
|| { rm ${userdir}/hdwarning.sh 2>/dev/null \
mv ${userdir}/hdwarning.log ${userdir}/hdwarning.log.bak 2>/dev/null }

hdwarning.sh

#!/bin/ksh
#檢測硬盤剩餘空間並警告的shell V050921
#四川省樂山市沙灣區郵政局 宋濤
#精簡代碼,改進增強
#增加當超標時,只在預先指定的前N位預先的指定用戶登錄時才顯示提示信息,
#即只有這前面N位用戶纔有可能及時反饋,避免當超標時接到過多的前臺反饋電話 V050923

#請先編輯指定用戶根下的 .profile ,在最後追加一行
#  test -x hdwarning.sh &&  ./hdwarning.sh
#若.profile最後已加入了自啓動專用程序命令行,則請在此行前面插入上述行

#簡單說明: 當指定用戶登錄後,若當前目錄中hdwarning.sh腳本存在(一般此
#時硬盤已用空間已經超標),則運行此腳本,並在屏幕顯示警告信息,此時終端
#操作人員應該及時將此信息把饋給預先指定的部門或預先指定的管理人員,
#以便作相應的處理.若未超標或已清理磁盤文件並達標,則將刪除腳本自身
#hdwarning.sh(取消登錄時的檢測和警告信息)

usedhd=80 #自定義超限已用硬盤空間大小比例,默認爲80%
loginnum=10 #自定義最初登錄反饋的用戶數,默認爲前 10 位
name="運維部" #接受反饋的部門或管理人員
tel="2113714 2110394" #接受反饋的部門或管理人員的聯繫方式或電話
test "$1" && userdir=$1 || userdir=/usr/scabs #前臺用戶的目錄(默認設爲統版用戶),也可在調用此
#腳本時加上指定前臺用戶的目錄參數
hdwaring()
{ ttyname=$(tty)
echo ${ttyname##*

shell cpu====================================================================:

/proc目路下的內存文件系統映射了系統的運行時的一些信息,包括進程列表,
內存信息,CPU使用情況,還有網絡等等
所以可以通過讀/proc下的文件來實現統計信息的獲取
但是,要注意的時不同的版本,將/proc下的每個文件中的類容會有一些差別,每一個項代表什麼要自己分析,最好根據top的輸出去分析
然後就可以通過shell教本或者C取得CPU使用率
比如:
我的機子是AS4(Kernel 2.6.9-5)
cat /proc/stat
cpu 1047871 11079 394341 1157538880 4909104 1945 61338
cpu0 352894 2950 157917 290318045 109839 0 49564
cpu1 234860 1978 115148 288108962 2522748 1028 6391
cpu2 106253 1674 52273 288601985 2225180 909 2839
cpu3 353863 4477 69001 290509888 51337 6 2543
intr 3021292348 2939335896 720 0 12 12 0 7 2 1 0 0 0 1951 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 7217173 0 0 0 0 0 0 0 30 0 0 0 0 0 0 0 74736544 0 0 0 0 0 0 0 0 0 0 0 0 0
ctxt 379682110
btime 1158715143
processes 603543
procs_running 1
procs_blocked 0
然後就可以自己計算了

#########GetCPU.sh
######Author:duanjigang
#!/bin/sh
while true
do
awk '$1=="cpu"{Total=$2+$3+$4+$5+$6+$7;print "Free: " $5/Total*100"%
" " Used: " (Total-$5)*100/Total"%"}' </proc/stat
sleep 1
done
複製代碼

#./GetCPU.sh
Free: 99.4532% Used: 0.546814%
Free: 99.4532% Used: 0.546813%
Free: 99.4532% Used: 0.546813%
Free: 99.4532% Used: 0.546813%
這樣應該可以的


shell cpu MEM====================================================================:


(1):取CPU使用率
機器:LinuxAS4 2.6.9-5.ELsmp (不通版本的內核會有差異的)
#cpu.sh-to get the utilization of every cpu
#author:duanjigang<2006/12/28>
#!/bin/sh
awk '$0 ~/cpu[0-9]/' /proc/stat | while read line
do
echo "$line" | awk '{total=$2+$3+$4+$5+$6+$7+$8;free=$5;\
print$1" Free "free/total*100"%",\
"Used " (total-free)/total*100"%"}'
done
複製代碼

#chmod +x cpu.sh
#./cpu.sh
cpu0 Free 99.7804% Used 0.219622%
cpu1 Free 99.8515% Used 0.148521%
cpu2 Free 99.6632% Used 0.336765%
cpu3 Free 99.6241% Used 0.375855%

(2)網絡流量情況
#if.sh-to get the network flow of each interface
#for my beloved ning
#author:duanjigang<2006/12/28>
#!/bin/sh
echo "name ByteRec PackRec ByteTran PackTran"
awk ' NR>2' /proc/net/dev | while read line
do
echo "$line" | awk -F ':' '{print " "$1" " $2}' |\
awk '{print $1" "$2 " "$3" "$10" "$11}'
done
複製代碼

#./if.sh
name ByteRec PackRec ByteTran PackTran
lo 2386061 17568 2386061 17568
eth0 1159936483 150753251 190980687 991835
eth1 0 0 0 0
sit0 0 0 0 0

(3):端口情況
http://bbs.chinaunix.net/viewthread.php?tid=864757&highlight=duanjigang
(4)至於內存
cat /proc/meminfo | grep "MemTotal"
cat /rpco/meninfo | grep "MemFree"
就可以了吧
發佈了36 篇原創文章 · 獲贊 16 · 訪問量 15萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章