Minimal FIFO named pipe example
You wonβt be able to see anything interesting in regular files, since they always give POLLIN immediately: How to select () wait on regular file descriptors (not sockets)?
The easiest way to play with poll is to use named pipes as shown below. This should prepare you for their main application: sockets and device files.
Source below. Using:
sudo mknod poll0.tmp p sudo mknod poll1.tmp p sudo chmod 666 poll*.tmp ./poll.out
In another shell:
printf a > poll0.tmp printf b > poll1.tmp
Output:
loop POLLIN i=0 n=1 buf=a loop POLLHUP i=0 loop POLLIN i=1 n=1 buf=b POLLHUP i=1 loop
So, note that poll expects reading without a loop.
Cooler example:
(while true; do date; sleep 1; done) > poll0.tmp & (while true; do date; sleep 2; done) > poll1.tmp &
0 recorded every second, and 1 every two seconds, which shows how poll() works with both inputs simultaneously, without stopping each other.
A source:
#define _XOPEN_SOURCE 700
Compile with:
gcc -o poll.out -std=c99 poll.c
Tested on Ubuntu 14.04.
GitHub upstream .
Rows:
close(pfds[i].fd); pfds[i].fd *= -1;
otherwise you will get POLLHUP forever, see also: How to use the C poll function to view named pipes in Linux?
For even more fun, create a Linux kernel module that implements poll fops: How do I add a polling function to the kernel module code?