在运行下面的代码时,其中一个 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);
回调是空的(无用),但这只是为了表明问题不在回调中。