Programming for Linux server CPU, memory, and disk utilization

Source: Internet
Author: User
Tags strcmp

Proc File System Introduction

The/proc file system is a pseudo-file system that only exists in memory and does not occupy external memory space. It provides the interface for the kernel to communicate with the process in a file system manner. Users and applications can get system information through/PROC, and can change certain parameters of the kernel. Because the information of the system, such as the process, is dynamically changed, so when a user or application reads a file from the/proc directory, the proc file system dynamically reads the required information from the system kernel and submits it.
There are some directory names in the/proc directory, which are the process directories. Each process currently running in the system corresponds to a directory/proc/pid that is the directory name of the process number under/proc, which is the interface that reads the process information. In addition, there is a task directory in the/proc/pid directory in the version above Linux 2.6.0-test6, and there are some directory/proc/pid/task/tid named for the thread number of threads owned by the process/proc/pid/task directory. They are interfaces that read thread information.

CPU Usage

To calculate the CPU usage, first understand the contents of the file/proc/stat, as follows, the contents of the file in the server I use:


Each parameter in the CPU and CPU0, CPU1, CPU2, CPU3, and CPU4 is interpreted as the meaning of each of the arguments (in the first example):
User (28201): accumulates from the start of the system to the current time, the CPU time (in jiffies), which does not include the nice value as a negative process. 1jiffies=0.01 sec
Nice (389): The CPU time (in jiffies) of a process that has a negative value from the moment the system starts to accumulate to the current time
System (10975): accumulates from the start of the boot to the current moment, core time (unit: jiffies)
Idle (6552431): accumulated from the start of the system to the current moment, in addition to the hard disk IO wait time other than the Wait time (unit: jiffies)
iowait (19704): accumulated from the start of the system to the current time, hard disk IO wait time (in jiffies),
IRQ (0): accumulate from the start of the system to the current moment, hard Interrupt time (unit: jiffies)
SOFTIRQ (208): accumulated from the start of the system to the current moment, soft interrupt time (unit: jiffies)

Ways to get CPU usage:

1. Record CPU usage at some point

2, wait for the last time period

3, and then record the CPU usage at the moment

4, calculate the total time slice

Sum all CPU usage for the first time, get J1, sum all CPU usage for the second time, get J2, then j2-j1 get all the time slices of this time period. That is, the total=j2-j1= of all columns of the second time and-all columns of the first

5. Calculate Idle Time

Idle corresponds to the fifth column of data, minus the first time with the second, idle= the second fifth column-the first fifth column

6. Calculate CPU Usage

Ate= (Total-idle)/total

The implementation in the code is as follows:

syscpuinfo* _gethostcpuinfo () {Syscpuinfo *cpuinfo = (Syscpuinfo *) malloc (sizeof (syscpuinfo)); if (cpuinfo = = NULL) err_ Dump ("_getcpuinfo:malloc struct syscpuinfo error"); FILE *fd;charbuff[256];memset (Buff, ' sscanf ', "n"), FD = fopen ("/proc/stat", "R"), Fgets (buff, sizeof), FD), (buff , "%s%lu%lu%lu%lu", Cpuinfo->name, &cpuinfo->user, &cpuinfo->nic, &cpuinfo->system, & Cpuinfo->idle); fclose (FD); return cpuinfo;} Float_calculatehostcpurate (Syscpuinfo *first, Syscpuinfo *second) {unsigned longold_cpu_time, new_CPU_Time;unsigned Longusr_time_diff, Sys_time_diff, nic_time_diff;float cpu_use = 0.0;old_cpu_time = (unsigned long) (First->user + First->nic + First->system + first->idle); new_cpu_time = (unsigned long) (Second->user + second->nic + Seco Nd->system + second->idle); Usr_time_diff = (unsigned long) (second->user-first->user); Sys_time_diff = ( unsigned long) (second->system-first->system); Nic_time_diff = (unsigned loNG) (second->nic-first->nic); if ((new_cpu_time-old_cpu_time)! = 0) Cpu_use = (float) 100* (Usr_time_diff + sys_Time _diff + Nic_time_diff)/(new_cpu_time-old_cpu_time); else Cpu_use = 0.0;return cpu_use;} Floatgethostcpurate () {float cpu_rate; Syscpuinfo *first, *second;first = _gethostcpuinfo (); sleep; second = _gethostcpuinfo (); cpu_rate = _ Calculatehostcpurate (first, second);/* Clean auxiliary Memory */free (first); free (second); first = Second = Null;return Cpu_rate;}
Memory Utilization

Memory usage calculation is convenient, you can directly call a Linux system library function SysInfo (), the function returns the following struct body:

struct sysinfo {long uptime;  /* Seconds since boot */unsigned long loads[3];  /* 1, 5, and minute load averages */unsigned long totalram;   /* Total usable main memory size */unsigned long freeram; /* Available Memory Size */unsigned long sharedram; /* Amount of Shared memory */unsigned long bufferram; /* Memory used by buffers */unsigned long totalswap;  /* Total swap space size */unsigned long freeswap;    /* Swap space still available */unsigned short procs; /* Number of current processes */unsigned long totalhigh;  /* Total high memory size */unsigned long freehigh;   /* Available High memory size */unsigned int mem_unit; /* Memory unit size in bytes */char _f[20-2*sizeof (LONG)-sizeof (int)]; /* Padding for LIBC5 */}; 
The Freeram in the struct represents the size of the available memory, and Totalram represents the total memory size. So with these two values you can calculate the memory usage. The code implementation is as follows:

Sysmeminfo *gethostmeminfo () {Sysmeminfo *meminfo = (Sysmeminfo *) malloc (sizeof (sysmeminfo)); if (NULL = = Meminfo)  Err_dump ("Getmeminfo:malloc sysmeminfo struct error"), struct sysinfo tmp;int ret = 0;ret = SysInfo (&tmp); if (ret = = 0 {Meminfo->memfree = (unsigned long) tmp.freeram/(1024*1024); meminfo->memtotal = (unsigned long) tmp.totalram/( 1024*1024);} else {err_dump ("Getmeminfo:sysinfo () Error");} return meminfo;}
Disk Utilization

It was intended to get the usage of the partition by reading the file/proc/partitions, but it would only get the size of the partition and the usage would not be available. However, you can read all the file system information in the system by reading the file/etc/mtab. It then counts the total disk size of all file systems and the total size of the disks that can be used to calculate the total disk utilization of the file system in the system. The code implementation is as follows:

Sysdiskinfo *gethostdiskinfo () {Sysdiskinfo *sys_disk_info = (Sysdiskinfo *) malloc (sizeof (sysdiskinfo));D iskinfo* Disk_info;struct statfsfs_info;struct Mntent*mnt_info; file*fh;floatpercent;unsigned longsum_total = 0, Total_free = 0;if ((fh = Setmntent ("/etc/mtab", "r")) = = NULL) {printf ("C Annot open/etc/mtab file!:%s\n ", Strerror (errno)); return NULL;} while ((Mnt_info = getmntent (FH)) = NULL) {if (Statfs (Mnt_info->mnt_dir, &fs_info) < 0) {continue;} if (Disk_info = (DiskInfo *) malloc (sizeof (diskinfo)) = = = NULL) {continue;} if (strcmp (Mnt_info->mnt_type, "proc") &&strcmp (Mnt_info->mnt_type, "Devfs") &&strcmp (Mnt_ Info->mnt_type, "Usbfs") &&strcmp (Mnt_info->mnt_type, "Sysfs") &&strcmp (Mnt_info->mnt_ Type, "Tmpfs") &&strcmp (Mnt_info->mnt_type, "devpts") &&strcmp (Mnt_info->mnt_type, "Fusectl") &AMP;&AMP;STRCMP (Mnt_info->mnt_type, "Debugfs") &&strcmp (Mnt_info->mnt_type, "Binfmt_misc") & &AMP;STRCMP (MNT_info->mnt_type, "Fuse.gvfs_fuse_daemon") &&strcmp (Mnt_info->mnt_type, "SECURITYFS")) {if (fs_info.f _blocks! = 0) {percent = ((float) fs_info.f_blocks-(float) fs_info.f_bfree * 100.0/(float) fs_info.f_blocks);} else {Perce NT = 0;}} else {continue;} strcpy (Disk_info->type, Mnt_info->mnt_type); strcpy (Disk_info->device, mnt_info->mnt_fsname); strcpy ( DISK_INFO-&GT;MNTPNT, mnt_info->mnt_dir); unsigned long block_size = Fs_info.f_bsize/1024;disk_info->blocks = FS _info.f_blocks * Block_size/1024;disk_info->bfree = Fs_info.f_bfree * Block_size/1024;disk_info->availiable_ Disk = Fs_info.f_bavail * block_size/1024;disk_info->bused = (fs_info.f_blocks-fs_info.f_bfree) * block_size/1024 ;d isk_info->bused_percent = percent;sum_total + = Disk_info->blocks;total_free + = Disk_info->availiable_disk ;/* Clean auxiliary Memory */free (disk_info);d isk_info = NULL;} Sys_disk_info->disk_total = Sum_total/1024;sys_disk_info->disk_free = total_free/1024;return sys_disk_info;} 





Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.