c++ - Two pcap_compile() on one device at same time? -


i have 2 threads , each 1 has packet capture same deviсe @ same time program crashes when second thread reaches pcap_compile() function. each thread has own variables , don't use global. seems same handle of device, therefore program crashes. why need 2 threads? because want seperate packets on sent , on recived specified pcap filter. how solve this? or better use 1 thread , sort manually sent , received packets using address tcp header?

pcap_compile not thread safe. must surround calls may encountered separate threads critical section/mutex prevent errors because of non thread-safe state within parser compiles expression (for gory details, uses yacc create code parsing expression , code generated eminently not thread safe).

you need explicitly open device once per thread you're planning on using capture, if reuse same device handle across multiple threads not you're asking for. should open pcap handle within thread you're planning on using it, each thread that's planning on doing capture should it's own pcap_open.

to guard call pcap_compile critical section, create simple wrapper (c++ wrapper of windows critical section):

class lock_interface { public:     virtual void lock() = 0;     virtual void unlock() = 0; };  class cs : public lock_interface {     critical_section crit; public:     cs() { initializecriticalsection(&crit); }     ~cs() { deletecriticalsection(&crit); }     virtual void lock() {         entercriticalsection(&crit);     }     virtual void unlock() {         leavecriticalsection(&crit);     } private:     cs(const locker &);     cs &operator=(const cs &); };  class locker {     lock_interface &m_ref; public:     locker(lock_interface &ref) : m_ref(ref) { m_ref.lock(); }     ~locker() { m_ref.unlock(); } private:     locker(const locker &);     locker &operator=(const locker &); };  static cs section;  int wrapped_pcap_compile(pcap_t *p, struct bpf_program *fp, const char *str, int optimize, bpf_u_int32 netmask) {     locker locked(section);     pcap_compile(p, fp, str, optimize, netmask); } 

Comments

Popular posts from this blog

ruby on rails - RuntimeError: Circular dependency detected while autoloading constant - ActiveAdmin.register Role -

c++ - OpenMP unpredictable overhead -

javascript - Wordpress slider, not displayed 100% width -