4

epoll_event で void *ptr を使用するのがますます難しくなっています。これを構造体にリンクできますか?たとえば、こんなことはできますか?私はこのようなことをしようとしていますが、うまくいかないため、リッスン ソケットの最初のループは良好ですが、別のイベントが発生するとクラッシュします。誰かが 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 );
        }
    }
}
4

1 に答える 1

13

void *ptrとのint fd両方が 内のユニオン内にありstruct epoll_eventます。両方ではなく、どちらかを使用する必要があります。したがって、構造体にフィールドを追加し、フィールド内fdの構造体へのポインタのみをリンクします。このようにして、ポインターを取得してから、さらに使用するためにポインターを取得します。ptrepoll_eventfd

于 2012-09-23T21:01:09.840 に答える