epoll_wait event.data.fd 始终为 0

epoll_wait event.data.fd is always 0

我正在尝试使用 epoll 设置一个基本服务器来处理多个客户端。但是,变量 socket(第 20 行)的值在第一次迭代时等于 0,但它应该是 3accept 套接字)。

事件已正确注册,但套接字值为 0。我尝试了不同的标志(EPOLLINEPOLLOUT),但没有任何变化。

这里是主要函数:

int main(int argc, char **argv)
{
    if (argc != 3)
        errx(1, "Usage: ./basic_server SERVER_IP SERVER_PORT");
    int cnx = prepare_socket(argv[1], argv[2]);

    int epoll_instance = epoll_create1(0);
    struct epoll_event event = {};
    event.events = EPOLLOUT | EPOLLIN;
    struct connection_t *queue = NULL;
    if (epoll_ctl(epoll_instance, EPOLL_CTL_ADD, cnx, &event) == -1)
        errx(1, "Failed to register server");
    while (1)
    {
        struct epoll_event events[MAX_EVENTS];
        int events_count = epoll_wait(epoll_instance, events, MAX_EVENTS, -1);
        for (int event_idx = 0; event_idx < events_count; event_idx++)
        {
            printf("%d\n", events[event_idx].data.fd);
            int socket = events[event_idx].data.fd;  // line 20
            if (socket == cnx)
                queue = accept_client(epoll_instance, socket, queue);
            else
                communicate(socket, queue);
        }
    }
    return 0;
}

struct epoll_event.data字段没有被操作系统触及,它只是与你添加到你的epoll实例然后返回的fd相关联原样 当事件发生时。如果您希望 event.data.fd 成为正确的文件描述符,那么您必须在调用 epoll_ctl:

之前设置它
struct epoll_event event = {};
event.data.fd = cnx; // <-- here
event.events = EPOLLOUT | EPOLLIN;

// ...

int events_count = epoll_wait(epoll_instance, events, MAX_EVENTS, -1);

// Now events[event_idx].data.fd == cnx as it should.