使用Nethogs监控进程的发送数据速率
先利用nethogs将进程的收发速率写进log文件,再对文件进行读取
1 #define SHELL "/bin/bash"
2 #include<string.h>
3 #include<stdlib.h>
4 #include<sys/time.h>
5 #include<stdio.h>
6 #include<unistd.h>
7 #include<iostream>
8 #include <sys/types.h>
9 #include <sys/wait.h>
10
11 static pid_t *childpid=NULL;/*ptr to array allocated at run-time*/
12 static int maxfd; /*from our open_max(), {Prox openmax}*/
13 float readdata(int pid);
//这里由于Nethogs打开之后需要关闭 而popen函数并不对于子进程进行操作,只是等命令进行完之后再进一步继续,因此需要重写popen函数,在pclose时对子进程kill
20 FILE *popen2(const char *cmdstring, const char *type)
21 {
22 int i, pfd[2];
23 pid_t pid;
24 FILE *fp;
25
26 /*only allow "r" or "w"*/
27 if(type[0] != 'r' && type[0]!='w' || type[1] != 0) {
28 errno=EINVAL;
29 return (NULL);
30 }
31 if(childpid == NULL) {
/*first time throngh, allocate zeroed out array for child pids*/
32 maxfd = sysconf(_SC_OPEN_MAX);
33 if((childpid =(pid_t*) calloc(maxfd, sizeof(pid_t))) == NULL){
34 return(NULL);
35 }
36 }
37 if(pipe(pfd) < 0){
38 return(NULL);
39 } //errno set by pipe()
40 if((pid = fork()) < 0){
41 return(NULL); //error set by fork()
42 }
43 else if(pid==0) {
/*child*/
44 if(*type