How to use epoll_event data.ptr
Asked Answered
B

1

5

I am having an increasingly hard time using the void *ptr in the epoll_event. I can just link this to a struct? For example, can I do something like this? Because I am trying todo something like this but it does not work, the first loop on the listen socket is good, but after another event comes in it crashes. Can someone help me out in understanding how to use data.ptr?

struct client { 
int fd; 
int connection_status;
};

struct epoll_event *events = NULL;
struct epoll_event ev;
struct client *c = new client;
struct client *event_c = NULL;

c.fd = (socket);

int efd = epoll_create1(0);
ev.data.fd = c.fd;
ev.events = EPOLLIN;
ev.data.ptr = c;
epoll_ctl ( efd , EPOLL_CTL_ADD , c.fd , &ev );

events = (struct epoll_event*)calloc ( XXX , sizeof event );

while(1) {
    int n = epoll_wait ( efd , events , XXX , -1 ); 
    for ( int i = 0 ; i  < n ; i++ ) {
        event_c = (struct client*) events[i].data.ptr;
        cout << "SOCKET: " << event_c->fd << endl;

        if (c->fd == events[i].data.fd ) {
            struct client *new_c = new client;
            struct epoll_event new_ev;
            struct sockaddr inaddr;
            sockletn_t in_len;
            int nfd = accept ( c->fd , &inaddr , &in_len );
            /* make socket non-blocking ... / error checking */
            new_c->fd = nfd;
            new_c->connection_status = 1;
            new_ev.data.fd = nfd;
            new_ev.events = EPOLLIN;
            new_ev.data.ptr = client;
            int r = epoll_ctl ( efd , EPOLL_CTL_ADD , nfd , &new_ev );
            continue;
         } else {
            ssize_t count;
            char buf[512];
            int count = read ( events[i].data.fd , buf , sizeof buf );
            // ... error checking blah blah blah

            int rc = write ( 1 , buf , count );
        }
    }
}
Brio answered 11/8, 2012 at 18:44 Comment(0)
D
13

The void *ptr and int fd both are inside a union inside the struct epoll_event. You should use either of them not both. Hence in your struct, add the field for fd as well and only link pointer to the struct in the ptr field of the epoll_event. This way when you get back your pointer then get the fd from it for further use.

Declinate answered 23/9, 2012 at 21:1 Comment(2)
Why can't we use both?Roby
Oh. I got it... It's a "union", then we can use on or another, not both... ok.. but nothing avoid us to use a ptr to a struct where we can set the fd and other data. Right?Roby

© 2022 - 2024 — McMap. All rights reserved.