linux 使用Nethogs监控进程的发送速率

本文介绍如何在Linux系统中运用Nethogs工具实时监控进程的网络发送速率,包括将数据写入日志文件及通过自定义的popen函数进行监控。在实际操作中,可能会遇到一些错误,但可以通过调试解决。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用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 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值