poll() waits indefinitely although timeout is specified
Your code is unconditionally calling recv()
even when there is no data to read. In fact, you are completely ignoring the fds.revents
field altogether if poll()
does not return an error/timeout.
Your loop should look more like this:
struct pollfd fds;
fds.fd = sock;
fds.events = POLLIN;
do {
r = poll(&fds, 1, TIMEOUT*1000);
if (r == -1) {
if (errno == EINTR) continue;
perror("poll() failed");
break;
}
else if (r == 0) {
printf("timeout expired");
break;
}
else if (fds.revents & POLLIN) {
r = recv(...);
if (r < 0) {
perror("recv() failed");
break;
}
else if (r == 0) {
printf("socket disconnected\n");
break;
}
else {
// process data as needed...
}
}
else if (fds.revents & (POLLERR | POLLNVAL)) {
printf("socket error\n");
break;
}
}
while (1);
close(sock);
What does poll() do with a timeout of 0?
It will return immediately:
If timeout is greater than zero, it specifies a maximum interval (in milliseconds) to wait for any file descriptor to become ready. If timeout is zero, then
poll()
will return without blocking. If the value of timeout is-1
, thepoll
blocks indefinitely.
, as of Mac OS X 10.5
;
Maximum interval to wait for the poll to complete, in milliseconds. If this value is 0,
poll()
will return immediately. If this value isINFTIM (-1)
,poll()
will block indefinitely until a condition is found.
, as of OpenBSD 3.8
Poll system call - is this infiniband communication?
The fact that poll returns with a timeout only means that the process is waiting for some communication event to occur. This openmpi faq page lists some ways to debug.
What does poll(NULL, 0, timeout) mean?
It is basically a longhand way of writing a sleep()
of timeout
duration.
Related Topics
Reading from a File in Assembly
How to Manage Permissions When Developing in a Docker Container
How to Suppress Warnings in Qt Creator
How to Handle Bash with Multiple Arguments for Multiple Options
What Is The Safest Way to Empty a Directory in *Nix
How to Efficiently Move Many Files to a New Server
Sharing Stdout Among Multiple Threads/Processes
Interprocess Communication via Pipes
Unix Cut Except Last Two Tokens
How to Create a Core File for My Crashed Program
What Are Best Parameters to Run Imagemagick to Convert Low Quality PDF to Images (For Ocr)
How to Enable The Docker Remote API on Windows
Check for Existence of Wget/Curl