源码如下:
//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\n",strerror(errno));
exit(EXIT_FAILURE);
}
if((flowTx_fd = open(FLOW_TX_FILE, O_RDONLY)) == -1){
fprintf(stderr, "TX_open: %s\n",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\n",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\n",strerror(errno));
}
RX_buf[data_size -1 ] = ‘\0‘;
if((data_size = read(flowTx_fd,TX_buf,sizeof(TX_buf))) == -1){
fprintf(stderr, "read_tx: %s\n",strerror(errno));
}
TX_buf[data_size -1 ] = ‘\0‘;
//JOSN格式 {"firstName":"Brett","lastName":"McLaughlin","email":"aaaa"}
fprintf(flowSt_pin,"{\"up_flow\":\"%s\",\"down_flow\":\"%s\"}\n",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;
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-11-07 19:25:02