使用libpcap简单示例的100%cpu使用率

Sal*_*lab 6 c linux network-programming libpcap

在运行下面的代码时,其中一个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;
}
Run Code Online (Sandbox Code Playgroud)

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

运行:./example "tcp"或您喜欢的过滤器.

正如您所看到的,它是典型示例,循环的main和回调函数: pcap_loop(descr, -1, my_callback, NULL);

回调是空的(无用),但它只是表明问题不在回调中.

Ant*_*nko 6

-1在这里指定了超时:

descr = pcap_open_live(dev, BUFSIZ, 1,-1, errbuf);
Run Code Online (Sandbox Code Playgroud)

它会pcap_loop变成一个繁忙的循环,因为它会poll立即连续超时.

1000如果您没有其他值的原因,请使用类似(毫秒)的内容.