c - how to check packet availability in libpcap -
i use libpcap capture packets, , need put packets fifo queue packet available. fifo queue shared 2 threads, 1 thread call pcap_next() , put packet fifo queue. thread fetch packet fifo queue. have relate mutex. below:
u_char* pkt; for(;;){ pkt = pcap_next(); lock(&mutex); some_process(pkt); insert(pkt, list); unlock(&mutext); }
the pcap_next() related packet buffer, if there no packet in buffer, pcap_next() blocked. if there is/are packet(s), each call of pcap_next() returns 1 packet.
it can fetch oen packet each lock-unlock operation pair, if packet arrival not frequent, fine. if packet arrival frequent, in buffer there many pending packets, bit resource-consuming don lock-unlock operation pair 1 packet.
what hope is: after processing , inserting packet, can check whether there packets available in packet buffer. if there are, continue processing , insertion. otherwise, unlock mutex , go loop.
is there workaround this?
try such as
/* * xxx - can fail on platforms , devices, * , there may issues select() on this. see * pcap_get_selectable_fd() man page details. */ pcap_fd = pcap_get_selectable_fd(p); pcap_setnonblock(p); /* xxx - check failure */ (;;) { fd_set fdset; struct timeval timeout; /* * wait batch of packets available. */ fd_zero(&fdset); fd_set(pcap_fd, &fdset); timeout.tv_sec = 1; timeout.tv_usec = 0; if (select(1, &fdset, null, null, &timeout) == -1) { report error; } else { lock(&mutex); pcap_dispatch(p, -1, callback, pointer-to-stuff); unlock(&mutex); } }
that way, lock mutex, process entire batch of packets, , unlock mutex. many os capture mechanisms deliver multiple packets in batch, there 1 lock/unlock pair per batch in case.
callback some_process(pkt);
, insert(pkt, list);
stuff.
it possible that, once you're done batch, next batch available, doesn't achieve absolute minimum of lock/unlock pairs; however, absolute minimum might lock out other thread significant period of time, can never make progress, lock , unlock around each batch might best.
Comments
Post a Comment