c++ - 如何过滤epoll事件?

标签 c++ c linux sockets epoll

假设我正在监听多个网络端口: 80 与 TCP 81-250 与 UDP

这需要多种不同的方式来处理输入。
- 端口 80 的新套接字(将新文件描述符添加到 epoll 列表)
- 从 80 端口的客户端套接字读取
- 从其他 170 个 UDP 端口中的任何一个读取

有很多不同的句柄,而我想使用 epoll 只对正在更新的句柄使用react。
有什么方法可以过滤 epoll 事件,以便每个事件都能获得所需的句柄,而无需遍历所有文件描述符?

提前致谢,
犯了罪

示例代码:

int epfd = epoll_create( 10 );

int tcpFd = createTCPSocket( 80 );
registerListenEvent( epfd, tcpFd );

int udpFds[ 170 ];
for ( int i = 0; i < 170; i++ ) {
  udpSockets[ i ] = createUdpSocket( 81 + i );
  registerUdpPacketEvent( epfd, udpFds[ i ] );
}

int tcpClientFds[ 256 ];
int tcpClientId = 0;

struct epoll_event events[ 64 ];

while ( 1 ) {
  int nfds = epoll_wait( epfd, events, 64, -1 );
  for ( int i = 0; i < nfds; i++ ) {
    struct epoll_event event = events[ i ];
    int fd = event.data.fd;

    // This kind of filtering can take quite a while
    if ( fd == tcpFd ) {
      int acceptedFd = accept( tcpFd );
      registerTcpClientEvent( epfd, acceptedFd );
      tcpClientFds[ tcpClientId++ ] = acceptedFd;
    } else {
      for ( int i = 0; i < 170; i++ )
        if ( udpFds[ i ] == fd ) {
          handleUdpMessage( fd );
          return;
        }
     for ( int i = 0; i < tcpClientId; i++ ) {
       if ( tcpClientFds[ i ] == fd ) {
         handleTcpMessage( fd );
         return;
       }
     }
    }
  }
}

您可以想象为每个事件执行 170 - 426 次循环的代价是相当大的。 我希望没有这个就可以确定事件。 这可能吗?

最佳答案

epoll() 告诉您触发事件的确切文件描述符。你不必去寻找它们。 Read the documentation举个例子。 epoll_wait() 为您提供一组 epoll_event 结构,每个满足的文件描述符一个。 epoll_event 结构有一个 fd 成员。您将为 EPOLLIN 事件注册您的个人套接字,然后每次 epoll_wait() 报告满意的事件时,您将根据需要从报告的套接字中读取。

关于c++ - 如何过滤epoll事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21817592/

相关文章:

c - 如何获取输入提示用户输入两个字符并使用它们进行交换?

c++ - 如何在caffe中提取图层的blob信息?

c++ - Visual C++ 生成错误 : Failed to register output

c - 如何修复我的代码?

c - 如何使用 CMake 确定 64 位有符号整数类型和 printf 说明符?

python - AWS EC2 : "Invalid command: terminate"

linux - 如何在 Ubuntu 12.04 上安装 "v4l1-compat.ko, videodev.ko, v4l2-common.ko"?

linux - 在 Centos 6.2 中删除 bash 历史记录

c++ - 如何计算 token C++ 中子字符串存在的次数

c++ - 在传递给参数时,为什么我不能在给定合适的构造函数的情况下隐式构造一个对象?