Understanding Linux poll(): Structure, Events, and How It Works
This article explains the Linux poll() system call, detailing its pollfd structure, event flags, parameters like nfds and timeout, return values, and step‑by‑step operation flow for reading and writing data, highlighting differences from select and its advantages on 32‑bit systems.
What is poll()
poll() is a Linux system call used for I/O multiplexing, allowing a program to monitor multiple file descriptors for readiness events.
Function prototype
<code>struct pollfd myfd[500];
int poll(struct pollfd *fds, nfds_t nfds, int timeout);
</code>pollfd structure
<code>struct pollfd {
int fd; // file descriptor to monitor
short events; // requested events
short revents; // returned events
};
</code>Event flags
pollfd.events and pollfd.revents can be set to the following flags:
Read events: POLLIN, POLLRDNORM, POLLRDBAND, POLLRI
Write events: POLLOUT, POLLWRNORM, POLLWRBAND
Error events: POLLERR, POLLHUP, POLLNVAL
Multiple flags can be combined using the bitwise OR operator, e.g., POLLIN | POLLOUT .
Parameters
nfds : the highest-numbered file descriptor in the pollfd array plus one.
timeout : timeout in milliseconds; >0 waits up to the specified time, =0 returns immediately, =-1 blocks indefinitely.
Return value
>0: number of file descriptors ready.
-1: error occurred.
How poll works
The typical workflow is:
Application fills a pollfd array with file descriptors and the events it wants to monitor.
Calling poll() copies this array into the kernel.
The kernel monitors the descriptors; when data arrives, DMA copies it to the kernel buffer and updates the corresponding revents field.
poll() returns; the application checks the return value and iterates the pollfd array to handle ready descriptors.
Key differences from select
poll introduces the pollfd structure, removing the 1024‑descriptor limit of select on 32‑bit systems and allowing the structure to be reused. However, poll is Linux‑specific, while select works on many platforms.
Lobster Programming
Sharing insights on technical analysis and exchange, making life better through technology.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.