Search code examples
clinuxsocketslibev

Libev - I/O callbacks


I have a chat server in C/Linux using TCP sockets. When using libev I am able to create an ev_io watcher for read events once for a socket. Something like:

ev_io* new_watcher = (ev_io*)malloc(sizeof(ev_io));

//initialize the watcher
ev_init(new_watcher, read_cb);

//set the fd and event to fire on write
ev_io_set(new_watcher, watcher->fd, EV_READ);

//start watching
ev_io_start(loop, new_watcher);

and this works fine because the read event will only fire when there is data to read. However, I have to treat write events differently because they are constantly firing even when I don't have data to write. To solve this problem I have my read_callback create an ev_io watcher for a write data only when there is data ready to be written, and then the write_callback will delete the watcher after it has sent it's message.

This means that I am allocating, initialising, setting, watching, unwatching and deallocating the write watcher each time I need to handle a message. I worry that I may be handling this incorrectly and inefficiently.

What is the best method for handling write_callback events in libev?

Thanks in advance.


Solution

  • The allocation can add some overhead, you could use a static variable instead of malloc, or malloc once and only free after the event loop is finished. You only need to set before write and unset after it succeeds. But yes, that's how it needs to be done.