代码工作了一段时间然后就停止了

标签 c multithreading sockets

我制作了一个应用程序来监控接口(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/

相关文章:

c - 运行 A 然后运行 ​​B 或运行 C

c++ - 是否可以使用 libcurl 禁用 HTTP Keep-Alive?

java - 无法使用InputStream读取API读取所有字节?

sockets - 套接字错误 10053 软件导致连接中止

Android 网络传输对象

c++ - 您可以将 Ada 泛型函数导出到 C++ 吗?

c - 我是否必须将映射的长度添加到 mmap 返回的带有 MAP_GROWSDOWN 和 MAP_STACK 标志的指针?

python - 你如何使这个 Python 词典线程安全?

java - 从 Marshmallow 升级到 Nougat 后,Android 方法性能突然变慢

C++ Unix 多线程 "under the hood"会发生什么?