zoukankan      html  css  js  c++  java
  • linux 流量统计小程序

    源代码例如以下:

    //2015/7/2 10:30:35
    //gino
    #include <stdio.h>
    #include <sys/stat.h>
    #include <sys/types.h>
    #include <fcntl.h>
    #include <stdlib.h>
    #include <errno.h>
    #include <string.h>
    
    
    #define FLOW_RX_FILE    "/sys/class/net/eth0/statistics/rx_bytes"
    #define FLOW_TX_FILE    "/sys/class/net/eth0/statistics/tx_bytes"
    #define FLOW_STATISTICS     "/tmp/statistics"
    #define DATA_BUF_SIZE       1024
    
    int main(int argc, char **argv){
    
            int flowRx_fd, flowTx_fd, flowSt_fd, data_size ;
            char RX_buf[DATA_BUF_SIZE] , TX_buf[DATA_BUF_SIZE];
            FILE *flowSt_pin = NULL;
    
            if((flowRx_fd = open(FLOW_RX_FILE, O_RDONLY)) == -1){
                fprintf(stderr, "RX_open: %s
    ",strerror(errno));
                exit(EXIT_FAILURE);
            }
    
            if((flowTx_fd = open(FLOW_TX_FILE, O_RDONLY)) == -1){
                fprintf(stderr, "TX_open: %s
    ",strerror(errno));
                exit(EXIT_FAILURE);
            }
    
            if((flowSt_fd = open(FLOW_STATISTICS, O_RDWR|O_CREAT, S_IRUSR|S_IWUSR)) == -1){
                fprintf(stderr, "ST_open: %s
    ",strerror(errno));
                exit(EXIT_FAILURE);
            }
    
            //将文件描写叙述符转换成文件指针
            flowSt_pin = fdopen(flowSt_fd, "w+");
    
            while(1){
    
                bzero(RX_buf,sizeof(RX_buf));
                bzero(TX_buf,sizeof(TX_buf));
    
    
                if((data_size = read(flowRx_fd,RX_buf,sizeof(RX_buf))) == -1){
                    fprintf(stderr, "read_rx: %s
    ",strerror(errno));
                }
                RX_buf[data_size -1 ] = '';
    
    
    
                if((data_size = read(flowTx_fd,TX_buf,sizeof(TX_buf))) == -1){
                    fprintf(stderr, "read_tx: %s
    ",strerror(errno));
                }
                TX_buf[data_size -1 ] = '';
    
    
    
    
                //JOSN格式  {"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
                fprintf(flowSt_pin,"{"up_flow":"%s","down_flow":"%s"}
    ",RX_buf, TX_buf);
                fflush(flowSt_pin);
    
                lseek(flowRx_fd, 0, SEEK_SET);
                lseek(flowTx_fd, 0, SEEK_SET);
    
    
                sleep(2);
    
                //更改文件大小。保存向文件里写入的数据达到覆盖效果
                ftruncate(flowSt_fd, 0);
            }
    
    
    
            return 0;
    }
    
  • 相关阅读:
    学习js笔记(第3章-语句和严格模式)
    学习js笔记(1,2章)
    学习闭包
    JavaScript 内存泄漏
    jQuery基础(四)—动画篇
    网站性能优化之yahoo军规
    webpack打包vue文件报错:Module parse failed: Unexpected token (1:0)
    PHP图片转为webp格式
    postman在phpstorm使用xdebug调试
    charles抓取手机APP,配置正确却抓不到数据
  • 原文地址:https://www.cnblogs.com/yjbjingcha/p/7203100.html
Copyright © 2011-2022 走看看