同时在 epoll 数据结构中使用 void *ptr 和 int fd

use of void *ptr and int fd in epoll data structure at same time

本文关键字:void ptr fd int epoll 数据结构      更新时间:2023-10-16

我正在使用epoll系统调用来处理TCP会话中的多个客户端。

我已经在 fd 注册了epoll

epoll_ctl (efd, EPOLL_CTL_ADD, fd, &event);

并且能够与比较FD一起使用:

if(conn->getSockfd() == events[i].data.fd)
    // ....

但作为 epoll 数据结构

typedef union epoll_data {
    void    *ptr;
    int      fd;
    uint32_t u32;
    uint64_t u64;
} epoll_data_t;

我想将一个对象(函数(映射到特定的fd字段,这样我就可以在比较后调用这个函数。

但我没有得到正确的结果。可以做还是不做?如果是,那么我可以使用它吗?

您正在为epoll_data_t使用联合。因此,它一次只能存储其中一个字段。所以要么你的空白*,int,随便什么。

我注意到你用C++标记了你的问题,所以这是我来解决这个问题的:

您可以在类/结构中将描述符和函数绑定在一起,然后为您接受/创建的每个连接创建一个新实例。在构造过程中,您可以将 FD 和函数传递到新对象中。

这是一个快速且未经测试的概念:

template < typename FunctionType >
struct Connection
{
    int FD;
    std::function< FunctionType >   DoStuff;
    Connection( int descriptor, const std::function< FunctionType >& Func )
      : FD      ( descriptor )
      , DoStuff ( Func )
}

然后你可以调用构造函数,将你的文件描述符和函数传递给它,用 std::bind 执行,然后通过执行 Connection.DoStuff(( 来调用它。

如果您使用占位符等,则可以使用参数等。有关 std::bind 和 std::function 的更多信息,请点击超链接。