使用libpcap简单示例时CPU占用率达到100%

7

在运行下面的代码时,其中一个CPU核心会达到100%的使用率,无论是否有流量。出了什么问题?

示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <pcap.h>
#include <errno.h>

void my_callback(u_char *args, const struct pcap_pkthdr* pkthdr, const u_char*
packet)
{
    //nothing, nothing at all...
    //printf("+");
}

int main(int argc,char **argv)
{
    int i;
    char *dev;
    char errbuf[PCAP_ERRBUF_SIZE];
    pcap_t* descr;
    const u_char *packet;
    struct bpf_program fp;        /* hold compiled program */
    bpf_u_int32 maskp;            /* subnet mask */
    bpf_u_int32 netp;             /* ip */

    if(argc != 2){
        fprintf(stdout, "Usage: %s \"expression\"\n"
            ,argv[0]);
        return 0;
    }

    /* Now get a device */
    dev = pcap_lookupdev(errbuf);

    if(dev == NULL) {
        fprintf(stderr, "%s\n", errbuf);
        exit(1);
    }
    /* Get the network address and mask */
    pcap_lookupnet(dev, &netp, &maskp, errbuf);
    /* open device for reading in promiscuous mode */
    descr = pcap_open_live(dev, BUFSIZ, 1,-1, errbuf);
    if(descr == NULL) {
        printf("pcap_open_live(): %s\n", errbuf);
        exit(1);
    }

    /* Now we'll compile the filter expression*/
    if(pcap_compile(descr, &fp, argv[1], 0, netp) == -1) {
        fprintf(stderr, "Error calling pcap_compile\n");
        exit(1);
    }

    /* set the filter */
    if(pcap_setfilter(descr, &fp) == -1) {
        fprintf(stderr, "Error setting filter\n");
        exit(1);
    }

    /* loop for callback function */
    pcap_loop(descr, -1, my_callback, NULL);
    return 0;
}

编译命令: gcc example.c -o example -lpcap

运行命令: ./example "tcp" 或使用你喜欢的筛选器。

正如您所看到的,这是一个典型的示例,包括循环的主要部分和回调函数: pcap_loop(descr, -1, my_callback, NULL);

回调函数为空(无用),但它只是为了说明问题不在于回调函数。

1个回答

7

您在这里指定了超时时间-1

descr = pcap_open_live(dev, BUFSIZ, 1,-1, errbuf);

这将把pcap_loop转换成忙循环,因为poll会持续立即超时。

如果没有其他原因,请使用类似于1000(毫秒)的值。


绝对是个聪明的做法。我曾经在一篇文章中听取建议,使用了-1来获得实时报告。但我没有意识到这会创建一个繁忙的循环。1毫秒对我来说已经足够避免默认批处理效果。CPU核心从最大化降至不到1%。 - Bill Tarbell

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接