事件轮询数据.fd提供给我一个随机值而不是c++

xmq68pz9  于 2023-08-09  发布在  其他
关注(0)|答案(1)|浏览(90)

我尝试注册一个事件轮询用于套接字目的,但是当我尝试使用epoll_ctl时,fd反而反映了一个随机(通常是负数)数。我在传入之前已经测试并确保fd是正确的,并且创建了epoll。有没有办法解决这个问题?如果你能帮忙的话,我将不胜感激。
这是在c++20,Linux Ubuntu 22.04编译的
这是一段代码

bool
service::engine::BListenerRunner::do_start_telnet_listener(void)
{
    m_socket_tcp_telnet_listener_p = new service::network::BSocketTcp(0, 5000, (60 * 60 * 1000), true);
    if (!m_socket_tcp_telnet_listener_p->do_listen())
    {
        // todo: log error
        return false;
    }

    std::cout << "Listening to port: " << m_socket_tcp_telnet_listener_p->port() << " on fd: " << m_socket_tcp_telnet_listener_p->fd() << std::endl;
    service::engine::BEventPollRunner::get_instance()->attach(m_socket_tcp_telnet_listener_p->fd(), m_socket_tcp_telnet_listener_p, shared::EVENT_POLL_IN);
    return true;
}

x

void
service::engine::BEventPollRunner::attach(int _fd, core::epoll::BEPollSubscriber* _subscriber_p, int _flag)
{
    struct epoll_event event;
    event.events = 0;
    event.data.fd = 0;
    event.data.ptr = (void*) _subscriber_p;

    // EVENT_POLL_IN / OUT is just an enum due to my code architecture, which ensures epoll library is included only in the correct source file.
    if ((_flag & shared::EVENT_POLL_IN)) event.events |= EPOLLIN;
    if ((_flag & shared::EVENT_POLL_OUT)) event.events |= EPOLLOUT;

    if (m_subscribers.find(_fd) == m_subscribers.end())
    {
        if (do_epoll_ctl(EPOLL_CTL_ADD, _fd, &event)) m_subscribers[_fd] = _subscriber_p;
        return;
    }

    do_epoll_ctl(EPOLL_CTL_MOD, _fd, &event);
}
bool
service::engine::BEventPollRunner::do_epoll_ctl(int _operation, int _fd, epoll_event* _event_p)
{
    int err = epoll_ctl(m_epoll_fd, _operation, _fd, _event_p);
    std::cout << "Adding fd " << _fd << " for op " << _operation << " on epfd " << m_epoll_fd << " err " << err << std::endl;
    if (err != 0)
    {
        switch (errno) // The errors have not implemented printing out.
        {
            case EBADF:
            {} break;
            case EEXIST:
            {} break;
            case EINVAL:
            {} break;
            case ENOENT:
            {} break;
            case ENOMEM:
            {} break;
            case EPERM:
            {} break;
        }

        return false;
    }

    return true;
}
epoll_event events[_EVENT_POLL_SIZE_];
int active_epoll = epoll_wait(m_epoll_fd, events, _EVENT_POLL_SIZE_, _EVENT_POLL_TIMEOUT_MS_);
if (active_epoll < 0)
{
    if (errno == EINTR) return;
    else
    {
        // todo: log warn/error
    }
}
    
for (int active = 0; active < active_epoll; ++active)
{
std::cout << "event fpoll fd: " << events[active].data.fd << std::endl;
}

的数据
在event_wait期间,显示的fd将是一个随机数,而不是假定的套接字fd。打印出来的套接字fd如下:

Adding fd 4 for op 1 on epfd 3 err 0
event fpoll fd: -604570616

的字符串

hm2xizp9

hm2xizp91#

感谢Igor Tandetnik的回复,我已经删除了ptr引用,现在它可以工作了。代码应该只分配fd或ptr本身,因为它是一个联合体。测试了一下,现在它工作了。

相关问题