c语言获取linux的CPU、内存、IO、磁盘、网速(本机编译通过)

摘要:
fgets(buff,sizeof(buff),fd);sscanf(buff,“%s%u%u%u%u”,o-˃名称,&o-˃用户,&o-˃nice,&o-˃系统,&o-˃idle);fclose(fd);}voidget_member_occupy(mem_occupy*mem){FILE*fd;charbuff[MAXBUFSIZE];fd=fopen(“/proc/meminfo”,“r”);fgets(buff,sizeof(buff),fd);sscanf(buff“%s%ld”,mem-˃name,&membe-˃total);fget(buff、sizeof(buff),fd;sscanv(buff”%s%ld“,mem-˃name2,&membe-˃free);}floatget_ io_ occupy(){charcmd[]=“iostat-d-x”;charbuffer[MAXBUFSIZE];chara[20];floatarr[20];FILE*管道=popen(cmd,“r”);if(!管道)return-1;fgets(缓冲区,sizeof(缓冲区),管道);fget(缓冲区、sizeof(缓存区)、管道)f%f%f%f“,a,&arr[0],&arr[1],&arr[2],&arr[3],&arr[4],&arr[5]&

代码:

    #include <stdio.h>  
    #include <stdlib.h>  
    #include <unistd.h>
    #include <string.h>   
    #define MAXBUFSIZE 1024
    #define WAIT_SECOND 3   //暂停时间,单位为“秒”  
    typedef  struct occupy        
    {  
        char name[20];      
        unsigned int user;  
        unsigned int nice;  
        unsigned int system;
        unsigned int idle;  
    } CPU_OCCUPY ;  
    
    typedef struct PACKED         
    {
        char name[20]; 
        long total; 
        char name2[20];
        long free;            
    }MEM_OCCUPY;

    float g_cpu_used;           
    int cpu_num;                //定义一个全局的int类型cup_num  
    void cal_occupy(CPU_OCCUPY *, CPU_OCCUPY *); 
    void get_occupy(CPU_OCCUPY *); 
    void get_mem_occupy(MEM_OCCUPY *) ;
    float get_io_occupy();
    void get_disk_occupy(char ** reused);
    void getCurrentDownloadRates(long int * save_rate);

    int main(){  
      CPU_OCCUPY ocpu,ncpu;
      MEM_OCCUPY mem;

      //获取cpu核数
      cpu_num = sysconf(_SC_NPROCESSORS_ONLN); 
      printf("cpu mum:%d
",cpu_num);
      
      //获取cpu使用率
      get_occupy(&ocpu);                     
      sleep(1);                                  
      get_occupy(&ncpu);                      
      cal_occupy(&ocpu, &ncpu); 
      printf("cpu used:%4.2f 
", g_cpu_used);  
      
      //获取内存使用率
      get_mem_occupy(&mem);

      double using = ((double)(mem.total - mem.free)/mem.total)*100;
      printf("mem used:%4.2f
",using);
      //获取io使用率
      printf("io used:%4.2f
",get_io_occupy());
      
      //获取当前磁盘的使用率
      char t[20]="";
      char *used = t;
       get_disk_occupy(&used);
       
      //char used[20]=" " ;
      //get_disk_occupy((char **)&used);
      printf("disk used:%s
",used);
      
      //网络延迟
        long int start_download_rates;  //保存开始时的流量计数  
        long int end_download_rates;    //保存结果时的流量计数  
        getCurrentDownloadRates(&start_download_rates);//获取当前流量,并保存在start_download_rates里  
        sleep(WAIT_SECOND); //休眠多少秒,这个值根据宏定义中的WAIT_SECOND的值来确定  
        getCurrentDownloadRates(&end_download_rates);//获取当前流量,并保存在end_download_rates里  
        printf("download is : %4.2f byte/s 
",( (float)(end_download_rates-start_download_rates))/WAIT_SECOND );
}
    void  cal_occupy (CPU_OCCUPY *o, CPU_OCCUPY *n){  
        double od, nd;  
        double id, sd;  
        double scale;    
        od = (double) (o->user + o->nice + o->system +o->idle);//第一次(用户+优先级+系统+空闲)的时间再赋给od  
        nd = (double) (n->user + n->nice + n->system +n->idle);//第二次(用户+优先级+系统+空闲)的时间再赋给od  
        scale = 100.0 / (float)(nd-od);       //100除强制转换(nd-od)之差为float类型再赋给scale这个变量  
        id = (double) (n->user - o->user);    //用户第一次和第二次的时间之差再赋给id  
        sd = (double) (n->system - o->system);//系统第一次和第二次的时间之差再赋给sd  
        g_cpu_used = ((sd+id)*100.0)/(nd-od); //((用户+系统)乖100)除(第一次和第二次的时间差)再赋给g_cpu_used  
    }  
    void  get_occupy (CPU_OCCUPY *o) {  
        FILE *fd;         
        int n;            
        char buff[MAXBUFSIZE];                                                                                               
        fd = fopen ("/proc/stat", "r"); //这里只读取stat文件的第一行及cpu总信息,如需获取每核cpu的使用情况,请分析stat文件的接下来几行。
        fgets (buff, sizeof(buff), fd); 
        sscanf (buff, "%s %u %u %u %u", o->name, &o->user, &o->nice,&o->system, &o->idle);  
       fclose(fd);     
    }  
    void get_mem_occupy(MEM_OCCUPY * mem){
        FILE * fd;
        char buff[MAXBUFSIZE];
        fd = fopen("/proc/meminfo","r");
        fgets (buff, sizeof(buff), fd); 
        sscanf (buff, "%s %ld", mem->name,&mem->total);  
        fgets (buff, sizeof(buff), fd); 
        sscanf (buff, "%s %ld", mem->name2,&mem->free); 
        }
    float get_io_occupy(){
            char cmd[] ="iostat -d -x";
            char buffer[MAXBUFSIZE];  
            char a[20];   
            float arr[20];
            FILE* pipe = popen(cmd, "r");    
            if (!pipe)  return -1;    
            fgets(buffer, sizeof(buffer), pipe);
            fgets(buffer, sizeof(buffer), pipe);
            fgets(buffer, sizeof(buffer), pipe);
            fgets(buffer, sizeof(buffer), pipe);
            sscanf(buffer,"%s %f %f %f %f %f %f %f %f %f %f %f %f %f ",a,&arr[0],&arr[1],&arr[2],&arr[3],&arr[4],&arr[5],&arr[6],&arr[7],&arr[8],&arr[9],&arr[10],&arr[11],&arr[12]);
            //printf("%f
",arr[12]);
            return arr[12];
            pclose(pipe);  
        }
    void get_disk_occupy(char ** reused){
        char currentDirectoryPath[ MAXBUFSIZE ];
        getcwd(currentDirectoryPath, MAXBUFSIZE);
        //printf("当前目录:%s
",currentDirectoryPath);
        char cmd[50]="df ";
        strcat(cmd,currentDirectoryPath);
        //printf("%s
",cmd);
        
        char buffer[MAXBUFSIZE];
        FILE* pipe = popen(cmd, "r");    
        char fileSys[20];
        char blocks[20];
        char used[20];
        char free[20];
        char percent[10];
        char moment[20];
        
        if (!pipe)  return ;  
        if(fgets(buffer, sizeof(buffer), pipe)!=NULL){
            sscanf(buffer,"%s %s %s %s %s %s",fileSys,blocks,used,free,percent,moment);
        }
        if(fgets(buffer, sizeof(buffer), pipe)!=NULL){
            sscanf(buffer,"%s %s %s %s %s %s",fileSys,blocks,used,free,percent,moment);
        }
        //printf("desk used:%s
",percent);
        strcpy(*reused,percent);
        return ;
    }
    
void getCurrentDownloadRates(long int * save_rate)  
{  
    char intface[] = "eth0:";  //这是网络接口名,根据主机配置
    //char intface[] = "wlan0:";
    FILE * net_dev_file;   
    char buffer[1024]; 
    size_t bytes_read; 
    char * match;  
    if ( (net_dev_file=fopen("/proc/net/dev", "r")) == NULL )
    {  
        printf("open file /proc/net/dev/ error!
");  
        exit(EXIT_FAILURE);  
    }  

  int i = 0;
    while(i++<20){
        if(fgets(buffer, sizeof(buffer), net_dev_file)!=NULL){
            if(strstr(buffer,intface)!=NULL){
                //printf("%d   %s
",i,buffer);
                sscanf(buffer,"%s %ld",buffer,save_rate);
                break;
            }
        }
        }
        if(i==20) *save_rate=0.01;
        fclose(net_dev_file); //关闭文件  
    return ;  
}

打印结果:

cpu mum:4
cpu used:1.25 
mem used:70.30
io used:0.10
disk used:4%
download is : 4963.33 byte/s 

免责声明:文章转载自《c语言获取linux的CPU、内存、IO、磁盘、网速(本机编译通过)》仅用于学习参考。如对内容有疑问,请及时联系本站处理。

上篇delphi Drag and Drop sample 鼠标拖放操作实例C#使用EventLog类操作系统日志(转)下篇

宿迁高防,2C2G15M,22元/月;香港BGP,2C5G5M,25元/月 雨云优惠码:MjYwNzM=

相关文章

gpio IOCTL控制

之前工作的时候,linux下用过GPIO的,无非就是配置输出输入模式,set/get value ,或者是gpio中断之类的,用户态配置GPIO主要是两种方式:用户态使用mmap直接将GPIO 地址映射过来,操作地址, 或者 IOCTL发命令给内核,内核来控制,最近半年都在写单片机的代码。时间久了有点忘了,最近使用都是偷懒直接使用了/sys下的设备,通过s...

(转)Linux修改eth2到eth0(70-persistent-net.rules)

之前在公司提供的虚拟机器上面,一直有个问题用着很不舒服,为什么它的IP选择的设备的eth2的,但是我在/etc/sysconfig/network-scrpts/下面也没有找到ifcfg-eth2的配置文件,这样子,我就没法修改IP了,也没法使用静态IP了,每次都是虚拟机动态分配的IP,这个太麻烦了。有时间解决了下这个问题。首先我声明下,我这里是用的NAT...

linux同步windows的时间

找了很多的资料,都没有windows做时间服务,linux同步windows的时间的,最后自己找了一些软件,终于搞定了,写出来给大家共享,以免大家多走弯路   首先在http://www.meinberg.de/english/sw/index.htm   下载了一个windows的NTP服务程序:ntp4171.zip   windows 192.168...

Linux下rsync的用法

一、rsync的概述 rsync是类unix系统下的数据镜像备份工具,从软件的命名上就可以看出来了——remote sync。rsync是Linux系统下的文件同步和数据传输工具,它采用“rsync”算法,可以将一个客户机和远程文件服务器之间的文件同步,也可以在本地系统中将数据从一个分区备份到另一个分区上。如果rsync在备份过程中出现了数据传输中断,恢复...

修改Kali Linux终端主题

修改KaliLinux背景图片在KaliLinux中,默认XFCE桌面背景图片保存在/usr/share/backgrounds/xfce目录。大学霸IT达人默认Undercover桌面背景图片保存在/usr/share/kali-undercover/backgrounds目录。如果用户不希望使用默认桌面,则可以将修改的背景图片保存到对应的目录。然后,依...

父进程非阻塞回收子进程(适用LINUX下C语言的clientserver模型)

      众所周知,子进程退出后(不管是正常还是异常退出),其父进程需要通过wait或waitpid来回收子进程的一些资源。回收是没有疑义的,但是父进程在哪儿回收,以什么方式回收,却影响着设计思路和效率。        一般的回收机制都属于阻塞回收,父进程阻塞等待子进程技术,收到子进程的退出状态。然而在实验中我需要实现的属于client-server模型...