Linux provides top, PS commands to view current CPU, mem usage, briefly described as follows:
One, using the PS view process resource consumption
Ps-aux
When you view process information, the third column is CPU consumption.
[Email protected] 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
Each column has the following meanings
USER PID%cpu%MEM VSZ RSS TTY STAT START time COMMAND
That is, the my_process process currently consumes CPU 3.4%, memory 0.9%
Second, top dynamic view system load
Top-n 1
Exit after display
[Email protected] utx86]# Top-n 1
Top-14:23:20 up 5: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. Get CPU Usage
[[email protected] 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
Explanation: 1.9%us is a user-occupied CPU condition
1.3%sy, is the system CPU usage
Get the value of the specific column:
[[email protected] utx86]# top-n 1 |grep Cpu | Cut-d ","-F 1 | Cut-d ":"-F 2
1.9%us
[[email protected] utx86]# top-n 1 |grep Cpu | Cut-d ","-F 2
1.3%sy
2. Get Memory usage
[Email protected] utx86]# top-n 1 |grep Mem
mem:2066240k Total, 1515784k used, 550456k free, 195336k buffers
Get memory condition specified column
[Email protected] c++_zp]# top-n 1 |grep Mem | Cut-d ","-F 1 | Cut-d ":"-F 2
2066240k Total
[Email protected] c++_zp]# top-n 1 |grep Mem | Cut-d ","-F 2
1585676k used
Third, the realization of programming
You can now save CPU usage, memory usage to a file by using the program
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;
}
Compile, run:
[Email protected] study]# g++ test.cpp
[Email protected] study]#./a.out
[email protected] study]# cat Cpu.txt
2.1%us
1.5%sy
2066240k Total
1619784K used
Four, hard disk usage programming implementation
1. HDD Usage Command DF-LH
2. Program implementation, call 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&nbs p; f_bsize; /* Optimal transfer block size */
long f_blocks; / * Total data blocks in file system */
long f_bfree; /* Free blocks in FS */
Lo ng f_bavail; /* Free blocks avail to Non-superuser */
long f_files; & nbsp; /* Total file nodes in file system */
long f_ffree; /* Free file nodes In FS */
fsid_t f_fsid; /* File System ID */
long f_namelen; /* m Aximum 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 Filena Me 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);
}
Shell
Monitoring Disk 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 $} ' | Sed ' s/%//g '
Echo $LOOK _out%
Sleep 1
Done
echo "Disk hda1 is nearly full!"
hdtest.sh
#!/bin/ksh
#检测硬盘剩余空间并警告的shell  v050921
#简单说明: This script can be added to crontab by the root user, the startup time is generally preferably set to a daily pre-business, when the script starts, such as detected that the used hard disk space exceeds the specified range, the hdwarning.sh script is copied to the specified user root directory; Otherwise, the hdwarning.sh script under the directory of the specified user is deleted.
Usedhd=80 #自定义超限已用硬盘空间大小比例, default is 80%
Test"$"&& userdir=$1 | |  userdir=/usr/scabs #前台用户的目录 (set to user by default), or add directory parameters to the specified foreground user when calling this script
hdwarning=$ (Df -v |sed'1d;s/.$//;s/\/dev\///'|awk'$6>' "$usedhd"'{print $,"=", $6"%"}')
Test"$hdwarning"&& { cp/usr/bin/hdwarning.sh ${userdir}/hdwarning.sh \
> ${userdir}/hdwarning.log  chmod 777 ${userdir}/hdwarning.sh ${userdir}/hdwarning.log} \
|| {&NBSPRM ${userdir}/hdwarning.sh 2>/dev/null \
MV ${userdir}/hdwarning.log ${userdir}/hdwarning.log.bak 2>/dev/null}
hdwarning.sh
#!/bin/ksh
#检测硬盘剩余空间并警告的shell  v050921
#增加当超标时, the prompt is displayed only when the pre-specified first n pre-specified user is logged on.
#即只有这前面N位用户才有可能及时反馈, avoid receiving too many front-desk feedback calls when exceeding the standard  v050923
#请先编辑指定用户根下的  .profile, append a row at the end
#  test -x hdwarning.sh &&  ./hdwarning.sh
#若. Profile has finally been added to the self-launching Special program command line, insert the preceding line before this line
#简单说明: When the specified user is logged in, the hdwarning.sh script in the current directory exists (typically this
#时硬盘已用空间已经超标), the script is run and a warning message is displayed on the screen, at which point the terminal
#操作人员应该及时将此信息把馈给预先指定的部门或预先指定的管理人员,
#以便作相应的处理. If the disk file is not exceeded or cleaned up, the script itself will be deleted
#hdwarning. SH (Detect and alert messages when logging off)
Usedhd=80 #自定义超限已用硬盘空间大小比例, default is 80%
loginnum=10 #自定义最初登录反馈的用户数, the default is the first &NBSP10 bit
Name="Operation and Maintenance Department"#接受反馈的部门或管理人员
Tel="2113714 2110394"#接受反馈的部门或管理人员的联系方式或电话
Test"$"&& userdir=$1 | |  userdir=/usr/scabs #前台用户的目录 (set to user by default), or you can call this
#脚本时加上指定前台用户的目录参数
Hdwaring ()
{ ttyname=$ (TTY)
Echo ${ttyname##*
Shell cpu====================================================================:
The memory file system under the/proc path maps some information about the runtime of the system, including the list of processes,
Memory information, CPU usage, network, etc.
So we can get the statistic information by reading the/proc file.
However, to be aware of the different versions, will be/proc under the class in each file will have some differences, each item represents what to analyze, it is best to analyze the output of the top
Then you can get CPU usage through shell textbook or C
Like what:
My machine is 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 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
And then you can figure it out for yourself.
- ######## #GetCPU. Sh
- ##### #Author:d Uanjigang
- #!/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
Copy Code
#./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%
This should be possible.
Shell CPU mem====================================================================:
(1): Take CPU utilization
Machine: LinuxAS4 2.6.9-5.ELSMP (the version of the kernel will be different)
- #cpu. Sh-to get the utilization of every CPU
- #author:d uanjigang<2006/12/28>
- #!/bin/sh
- awk ' $ ~/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
Copy Code
#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) network traffic situation
- #if. Sh-to get the network flow of each interface
- #for my Beloved Ning
- #author:d uanjigang<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 ' "$" "$ |\"
- awk ' {print $ ' "$" "$" "$" "$" "$11} '
- Done
Copy Code
#./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): Port condition
Http://bbs.chinaunix.net/viewthread.php?tid=864757&highlight=duanjigang
(4) As for memory
Cat/proc/meminfo | grep "Memtotal"
Cat/rpco/meninfo | grep "Memfree"
It's okay.
The compute memory utilization needs to be/proc/meminfofile with the corresponding data, the contents of the file are as follows:memtotal:1024008 KBmemfree:18448 KBbuffers:12664 KBcached:282500 KBswapcached:716 KBactive:816124 KBinactive:52516 KBhightotal:122500 KBhighfree:304 KB... MemtotalThe value represents the total amount of memory,Memfreenumeric value indicates the amount of spare. so
the real-time utilization of memory calculation formula
: (memtotal-memfree)/Memtotal
Install the principle of the previous article, using C to write a program to calculate CPU and memory utilization:
/*************************************************************LE:STATUSINFO.C * * @brief: Get CPU from Linux system and Memory Usage * * @version 1.0 * ***************************************************************/#include <stdio.h> #i Nclude <stdlib.h> #include <string.h>typedef struct PACKED//define a CPU Occupy structure body {char name[20]; Defines the array name of a char type name has 20 elements unsigned int user; Defines an unsigned int of type userunsigned int nice; Defines an unsigned int of type niceunsigned int system;//defines an unsigned int of type systemunsigned int idle; Defines an unsigned int of type idleunsigned int lowait;unsigned int irq;unsigned int SOFTIRQ;} cpu_occupy;typedef struct __mem{//unsigned char name[20];float total;float free;} Mem;int Get_meminfo () {mem Meminfo;memset (&meminfo,0x00,sizeof (MEM)); file* fp = fopen ("/proc/meminfo", "R"), if (fp = = NULL) {printf ("Can not open file\r\n"); return 0;} Char Buf[64];char name[32];memset (buf,0x00,sizeof (BUF)); Fgets (Buf,sizeof (BUF), FP); SSCANF (buf, "%s%f%s",name,& Meminfo.total,name); memset (BUF,0x00,sizeof (BUF)); Fgets (Buf,sizeof (BUF), FP), sscanf (buf, "%s%f%s", name,&meminfo.free,name);p rintf ("BUF is%s Name is%s%f\r\n ", buf,name,meminfo.free), float temp;sscanf (buf,"%s%f%s ", name,&temp,name);p rintf (" temp is%f \ r \ n ", temp);d ouble rate = (meminfo.total-meminfo.free)/meminfo.total;printf ("%f%frate is%f\r\n ", Meminfo.total, Meminfo.free,rate); fclose (FP); return 1;} int Cal_cpuoccupy (cpu_occupy *o, cpu_occupy *n) {unsigned long od, ND; unsigned long id, sd;double cpu_use = 0; OD = (unsigned long) (O->user + o->nice + o->system +o->idle + o->lowait + O->IRQ + O->SOFTIRQ);//First time (User + priority + system + Idle) time is re-assigned to ODND = (unsigned long) (N->user + n->nice + n->system +n->idle + n->lowait + N->IRQ + N->SOFTIRQ);//second (user + priority + system + Idle) time is then assigned to oddouble sum = nd-od;double Idle = N->idle-o->idle;cpu_use = Idle/sum; printf ("%f\r\n", cpu_use); idle = N->user + N->system + n->nice-o->user-o->system-o->nice;cpu_use = ID Le/sum;printf ("%f\r\n", Cpu_use); return 0;} void Get_cpuoccupy (Cpu_occupy *cpust)//The pointer to the untyped get function containing a formal parameter struct class o{the FILE *fd; int n; Char buff[256]; Cpu_occupy *CPU_OCCUPY;CPU_OCCUPY=CPUST;FD = fopen ("/proc/stat", "R"); Fgets (buff, sizeof (buff), FD);p rintf ("%s\r\n", Buff); sscanf (Buff, "%s%u%u%u,%u%u%u%u", Cpu_occupy->name, &CP U_occupy->user, &cpu_occupy->nice,&cpu_occupy->system, &cpu_occupy->idle,&cpu_ OCCUPY->LOWAIT,&CPU_OCCUPY->IRQ,&CPU_OCCUPY->SOFTIRQ);p rintf ("%s%u%u,%u,%u%u%u\r\n", cpu_ Occupy->name,cpu_occupy->user, Cpu_occupy->nice,cpu_occupy->system, cpu_occupy->idle,cpu_occupy- >LOWAIT,CPU_OCCUPY->IRQ,CPU_OCCUPY->SOFTIRQ);p rintf ("%s%u\r\n", cpu_occupy->name,cpu_occupy-> user); fclose (FD); }int Main () {cpu_occupy cpu_stat1; Cpu_occupy Cpu_stat2; Mem_occupy mem_stat;int cpu;//Get CPU usage for the first time get_cpuoccupy ((cpu_occupy *) &CPU_STAT1); sleep (10);//Get CPU usage for the second time get _cpuoccupy ((cpu_occupy*) &CPU_STAT2);//compute CPU Utilization CPU = Cal_cpuoccupy ((cpu_occupy *) &CPU_STAT1, (Cpu_occupy *) &cpu_stat2);p rintf ( "%d \ r \ n", CPU); Get memory Get_meminfo (); return 0;}
Programming for Linux CPU Usage memory usage