Search code examples
libevent

libevent cannot read an open socket descriptor


recently, I have a small socket server program using libevent.

In summary, it does following job.

void read_function(int fd, short event, void* arg) {
    printf("callback is called!\n");

    // read from fd, and send a reply to fd!
}

void accept_thread_function() {
    int fd = accept(...);
    struct event* ev_read = new struct event();
    memset(ev_read, 0, sizeof(struct event));
    event_set(ev_read, fd, EV_READ|EV_PERSIST,read_function,ev_read);
    event_add(ev_read, 0);
}

int main() {
    event_init();
    THREAD a = start 'accept_thread_function' as a thread;
    event_dispatch();
    THREAD::join(a);
}

The problem is, the read_function is never called.

Incoming connection is correctly accepted. (sigh)

I'm waiting for your kind comment about this problem.

Thank you in advance.


Solution

  • First, take a look at the (free) wonderful book on libevent written by Nick Mathewson :

    http://www.wangafu.net/~nickm/libevent-book/Ref1_libsetup.html#_locks_and_threading

    Then, you need to make sure that the event is added before the call to event_dispatch().