2
votes

Is there any way to associate callback functions with sockets in Linux?

For example, After connect(s, (struct sockaddr *)peeraddr, sizeof(*peeraddr)) function has connected client with server, is there a way to associate a function- afterRecv with socket- s such that after recv function has read some data from socket, afterRecv gets called?

My socket is of blocking type. The reason behind this kind of requirement is, I am working with a OpenSSL which does many send/recv calls on socket during handshake period internally. If I modify OpenSSL then it would be quite cumbersome to modify each and every recv. So I was thinking if I can add callback that would make my job easy.

The flow should be:

  1. Socket connection logic

  2. Recv function

  3. After recv has read data, afterRecv gets called as a callback on recv

1
As you seem to be planing to recompile OpenSSL's sources, replacing recv() by your own version (wrapping around the original recv()) would do the job, wouldn't it? - alk
@alk Yes, that seems a good option. - jshag
if you're open to using C++ the boost ASIO library has fantastic support for event-driven I/O and SSL. - Sam Miller

1 Answers

3
votes

Some event libraries implement such callback hooks:

and all graphical or HTTP server libraries (e.g. Gtk/Glib, Qt, LibOnion, ...) provide (or use) such event libraries (around a multiplexing syscall like poll(2) etc).

Both Glib (from GTK) and QtCore (from Qt) are event libraries usable without any GUI

Read also about the C10K problem