Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

libevent and non-blocking sockets

I understand that in order to monitor a socket using libevent, event_set() should first be called with the correct parameters.

The libevent documentation states that the event parameter to event_set() can be either EV_READ or EV_WRITE. And that this event parameter is the event to look out for.

But what socket events do EV_READ and EV_WRITE correspond to? I mean how would I monitor for a change in connection status, versus monitor for an incoming message?

like image 881
BeeBand Avatar asked Jun 04 '11 22:06

BeeBand


1 Answers

I've found this site to be excellent in terms of documentation for libevent. On the page dealing with events, there's a nice overview of what different event flags actually mean. From that link:

  • EV_READ : This flag indicates an event that becomes active when the provided file descriptor is ready for reading.

  • EV_WRITE : This flag indicates an event that becomes active when the provided file descriptor is ready for writing.

  • EV_SIGNAL : Used to implement signal detection.

  • EV_PERSIST : Indicates that the event is persistent.

  • EV_ET : Indicates that the event should be edge-triggered, if the underlying event_base backend supports edge-triggered events. This affects the semantics of EV_READ and EV_WRITE.

So to answer your question explicitly: EV_READ corresponds to having data available to be read from the socket or bufferevent, which are the libevent socket equivalents as far as I can tell. EV_WRITE corresponds to the socket/bufferevent being ready to have data written to it. You can set read / write callbacks to actually do the data reading and writing with the cb argument to

struct event *event_new(struct event_base *base, evutil_socket_t fd, short what, event_callback_fn cb, void *arg);

If you're doing socket IO with libevent, though, you may really want to consider using buffer events - they're what I use in one of my projects, snot_mon, which you can check out over on github.

like image 116
Peter Downs Avatar answered Oct 13 '22 19:10

Peter Downs