c++ - 在 C++ 中使用 pthread 时出现编译错误

标签 c++ multithreading pthreads

我正在用 C++ 编写一个嗅探器类,代码如下。

#include "Capture.h"
#include <sys/socket.h>
#include <cstring>
#include <linux/if_ether.h>
#include <netinet/ip.h>
#include <netinet/tcp.h>
#include <pthread.h>

Capture::Capture(int sniff_socket): sniff_socket_(sniff_socket), sniff_threadID_(0)
{
}

bool Capture::endCapture()
{
  if(!sniff_threadID_)
    return false;
  cout << "Asking capture thread to stop\n" <<endl;
  return !pthread_cancel(sniff_threadID_);
}

bool Capture::startCapture()
{
  if(pthread_create(&sniff_threadID_, NULL, Capture::sniffer_thread, NULL)) {
    cerr << "Unable to create capture thread"<<endl;
    return false;
  }
  return true;
}

void *Capture::sniffer_thread(void *)
{
  int MTU = 2048;
  char buffer[MTU];
  ssize_t msg_len;
  struct iphdr *ip_header;
  struct ethhdr *eth_header;
  struct tcphdr *tcp_header;
  void *packet;

  pthread_setcanceltype(PTHREAD_CANCEL_DEFERRED, NULL);
  while (1) {
    msg_len = recvfrom(sniff_socket_, buffer, MTU, 0, NULL, NULL);
    eth_header = (struct ethhdr*)buffer;
    ip_header = (iphdr*)(buffer + sizeof(ethhdr));
    tcp_header = (struct tcphdr*)(buffer + sizeof(struct ethhdr) + sizeof(struct iphdr));

    if(msg_len != -1){
      packet = malloc(msg_len);
      memcpy(packet, buffer, msg_len);
      pthread_testcancel();
      //queue add should be here
    } else {
      cerr<<"Error capture thread recvfrom"<<endl;
      pthread_exit(NULL);
    }
  }
  return NULL;
}

Capture::~Capture()
{
  // TODO Auto-generated destructor stub
}

但是,当我编译代码的时候,g++是这样说的

../Capture.cpp: In member function ‘bool Capture::startCapture()’:
../Capture.cpp:30: error: argument of type ‘void* (Capture::)(void*)’ does not match ‘void* (*)(void*)’

有人可以帮我解决这个问题吗?

最佳答案

C++ 类中的成员函数将this 作为隐藏参数传递,C 函数pthread_create 无法理解this 是什么,因为静态成员函数不要传递 this 你可以使用这样的静态函数:

class Capture
{
    public:
        static void *sniffer_thread(void*);
};



pthread_create(..., Capture::sniffer_thread, NULL);

关于c++ - 在 C++ 中使用 pthread 时出现编译错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5847334/

相关文章:

java - 如何在不同线程的回调内通知 ArrayAdapter 中的DataSetChanged? - 安卓

连接到 Redis 时永远不会终止的 Objective-C 控制台应用程序

c - 向等待锁的线程发出信号,表明该锁已变得无关紧要

pthreads - 在MingW下编译简单的pthread代码时出现链接器错误

c++ - std::function 析构函数中的段错误

c++ - vundle 不能与 ftplugin 一起正常工作

c++ - 如何序列化类型 boost::labeled_graph

c++ - QNetworkConfigurationManager::allConfigurations() 没有列出 WLAN

c# - GUI在获取数据时未响应

c - 使用 fork() 作为线程应用程序的后台