poll() — Linux system interface
Wait for events on an array of descriptors. Set events to requested bits and read revents after success; POLLERR, POLLHUP and POLLNVAL can appear without being requested. Timeout is milliseconds: zero checks immediately, negative waits indefinitely. Readiness is not a reservation; nonblocking operations remain useful if state changes. A positive result counts entries with nonzero revents, not bytes. EINTR requires deadline-aware handling. Compile the complete C example in a fresh private working directory using gcc -std=c17 -Wall -Wextra -Wpedantic -Werror example.c -o example; run ./example. POSIX interface; tested on Linux/glibc only. These are libc-facing signatures, not raw architecture-specific syscall ABIs.
Formal Syntax & Structure
#include <poll.h>int poll(struct pollfd *fds, nfds_t nfds, int timeout);Parameters & Attributes
| Name | Type | Description |
|---|---|---|
| fds | struct pollfd * | Array of descriptor/event records. |
| nfds | nfds_t | Number of array entries. |
| timeout | int | Milliseconds, zero for immediate check, negative for indefinite. |
Return Value
Positive ready entry count, 0 on timeout. On failure, returns -1 and sets errno.
Working Example
#define _GNU_SOURCE#define _POSIX_C_SOURCE 200809L#include <errno.h>#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <poll.h>
/* A failed check ends this short-lived demonstration. */#define CHECK(x) do { if (!(x)) { \ fprintf(stderr, "check failed at line %d: %s\n", __LINE__, #x); \ return EXIT_FAILURE; \} } while (0)
int main(void){ int f[2]; char b; CHECK(pipe(f) == 0); struct pollfd pfd = { .fd=f[0], .events=POLLIN }; CHECK(poll(&pfd, 1, 0) == 0); CHECK(write(f[1], "p", 1) == 1); CHECK(poll(&pfd, 1, 1000) == 1 && (pfd.revents & POLLIN)); CHECK(read(f[0], &b, 1) == 1 && b == 'p'); CHECK(close(f[1]) == 0); CHECK(poll(&pfd, 1, 1000) == 1 && (pfd.revents & POLLHUP)); CHECK(close(f[0]) == 0); puts("timeout; readable; hangup"); return EXIT_SUCCESS;}