Magical Epoll

shashank Jain
3 min readAug 5, 2018

--

In previous blog (https://medium.com/@jain.sm/concurrency-models-for-cloud-applications-3be99edd8888) we discussed on details of different threading models and in particular focused on epoll for event based multiplexing based on both level and edge triggered notifications.

In this blog We showcase on how to use the epoll mechanism we discussed in last blog to create a simple program to understand various stages of epoll from creation to registering the fds and then waiting for those fds to be in a ready state.

For this example we just use the FD 0 which is nothing but the stdin of the process to register with epoll.

We start explain with portions of sample code

In the above snippet, the epoll_create1 system call is made. The return of it is the epollfd , which will be used to trigger further system calls.

This system call epoll_ctl is used to register the fd and the specific event on this fd. The EPOLLIN event is used to register a read event and EPOLLOUT is used write events. So in the above case we register read events on stdin.

Next we see an infinite loop is started and inside that the first system call is EPOLL_WAIT. This system call takes as input the epoll fd.

Now here we have created the buffer size of 10 for reading the data.

So lets now launch the program and feed some data to it

On feeding test to stdin, the data is less then the buffer size so immediately we see one fd ready event and again the loop via next epoll_wait goes into blocked state

Next we feed in data size more then buffer

We see how the level trigger mechanism works. In this case as we see the buffer is 10 bytes and even if there was more data to be read on stdin the epoll_wait system call didn’t block. Every time the epoll_wait call happened, it checked if there is remaining data in the fd the process is notified to drain the remaining data and not block. Had it been an edge triggered mechanism, the epoll_wait would block unless we make the FD non blocking and keep draining till it gets EWOULDBLOCK and EAGAIN errors.

The example explained above is taken from https://suchprogramming.com/epoll-in-3-easy-steps/

Disclaimer : The views expressed above are personal and not of the company I work for.

--

--