我已经做了一个应用程序,监控一个接口,并返回一个数据包每秒阅读,如何执行时,它运行良好约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对于保留缓冲区有一些内部最大值。 IOW:阅读文档或一些示例代码,搜索一个函数来执行某种自由/释放/清理操作。 – hyde