首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

编程获取Linux的cpu占用率跟 mem使用情况

2012-09-27 
编程获取Linux的cpu占用率和 mem使用情况?1.9%us[root@localhost utx86]# top -n 1 |grep Cpu | cut -d ,

编程获取Linux的cpu占用率和 mem使用情况

?

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

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:

?


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&nbspV050921

#简单说明:?可由root用户将此脚本加入crontab,启动时间一般最好设为每天营业前,当此脚本启动时如检测到已用硬盘空间超过指定范围,则将hdwarning.sh脚本拷贝到指定用户根目录下;否则将删除指定用户的目录下的hdwarning.sh脚本.

usedhd=80???????????#自定义超限已用硬盘空间大小比例,默认为80%
test?"$1"?&&&nbspuserdir=$1?||&nbspuserdir=/usr/scabs??#前台用户的目录(默认设为统版用户),也可在调用此脚本时加上指定前台用户的目录参数

hdwarning=$(df&nbsp-v?|sed?'1d;s/.$//;s/\/dev\///'|awk?'$6>'"$usedhd"'?{print?$2,"?=?",$6"%"}')
test?"$hdwarning"?&&?{&nbspcp?/usr/bin/hdwarning.sh?${userdir}/hdwarning.sh??\
>?${userdir}/hdwarning.log?&nbspchmod&nbsp777?${userdir}/hdwarning.sh?${userdir}/hdwarning.log??}?\
||?{&nbsprm?${userdir}/hdwarning.sh&nbsp2>/dev/null??\
mv?${userdir}/hdwarning.log?${userdir}/hdwarning.log.bak&nbsp2>/dev/null??}

hdwarning.sh

#!/bin/ksh
#检测硬盘剩余空间并警告的shell&nbspV050921
#增加当超标时,只在预先指定的前N位预先的指定用户登录时才显示提示信息,
#即只有这前面N位用户才有可能及时反馈,避免当超标时接到过多的前台反馈电话&nbspV050923

#请先编辑指定用户根下的&nbsp.profile?,在最后追加一行
#?&nbsptest&nbsp-x&nbsphdwarning.sh?&&?&nbsp./hdwarning.sh
#若.profile最后已加入了自启动专用程序命令行,则请在此行前面插入上述行

#简单说明:?当指定用户登录后,若当前目录中hdwarning.sh脚本存在(一般此
#时硬盘已用空间已经超标),则运行此脚本,并在屏幕显示警告信息,此时终端
#操作人员应该及时将此信息把馈给预先指定的部门或预先指定的管理人员,
#以便作相应的处理.若未超标或已清理磁盘文件并达标,则将删除脚本自身
#hdwarning.sh(取消登录时的检测和警告信息)

usedhd=80???????????????#自定义超限已用硬盘空间大小比例,默认为80%
loginnum=10?????????????#自定义最初登录反馈的用户数,默认为前&nbsp10?位
name="运维部"???????????#接受反馈的部门或管理人员??
tel="2113714&nbsp2110394"???#接受反馈的部门或管理人员的联系方式或电话
test?"$1"?&&&nbspuserdir=$1?||&nbspuserdir=/usr/scabs??#前台用户的目录(默认设为统版用户),也可在调用此
#脚本时加上指定前台用户的目录参数
hdwaring()
{&nbspttyname=$(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
然后就可以自己计算了

" " 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 (不通版本的内核会有差异的)
? ?? ?? ?? ?? ?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)网络流量情况
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"
就可以了吧

?

?

?

?

?

热点排行