我制作了一个应用程序来监控接口(interface)并每秒返回一个数据包读数,但是在执行时它可以正常运行大约 30 秒,直到我打开 YouTube 页面使计数器运行得有点高。几秒钟后,应用程序卡住并且什么也不做。这发生在不规则的时间间隔内,所以我猜测它与计数有关,这是代码,它是用 C 语言编写的。
#include <stdio.h>
#include <pcap.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <time.h>
#include <pthread.h>
void callThreads(u_char *useless, const struct pcap_pkthdr* pkthdr, const u_char* packet);
void *packetcalc(void *threadid);
static struct timespec time1, time2;
static int t = 0, i = 0;
static long rc;
static pthread_t threads[1];
int main(int argc, char *argv[]){
pcap_t* descr;
char errbuf[PCAP_ERRBUF_SIZE];
descr = pcap_open_live("eth0", BUFSIZ, 1, -1, errbuf);
if(descr == NULL){
printf("Error: pcap_open_live()\n");
return 1;
}
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
pcap_loop(descr, 0, callThreads, NULL);
return 0;
}
void callThreads(u_char *useless, const struct pcap_pkthdr* pkthdr, const u_char* packet){
if(i >= 2147483647){
//In case i gets full from counting too many packets
i = 0;
time1.tv_sec = 0;
}
++i;
rc = pthread_create(&threads[t], NULL, packetcalc, (void *) t);
}
void *packetcalc(void *threadid){
static int j;
static int temp = 0;
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &time1);
if(temp != time1.tv_sec){
j = (i / time1.tv_sec);
printf("Packets: %d/sec\t(%d)\t(%d)\n", j, i, (int)time1.tv_sec);
temp = time1.tv_sec;
}
pthread_exit(NULL);
}
编辑:是否也可能是因为多线程,我在只分配了 1 个 CPU 的虚拟机中运行这段代码?
最佳答案
您正在为每个数据包创建一个线程,这是一个糟糕的想法。从你给 pcap_loop(3)
的回调函数中打印你需要的任何计数器就足够了。 .
关于代码工作了一段时间然后就停止了,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13800824/