I am new to socket programming and I’m trying to figure out how poll works. So I made a little example program. The program seems to work as how I expect it to, but when I comment out the line that has int dummy the for loop only runs one iteration when it’s suppose to do ten. What I don’t understand is how that variable has anything to do with the for loop. The program is suppose to print “timeout” after 3.5 secs and print “return hit” if there is input available.
#include <stdio.h>
#include <poll.h>
int main(int argc, char *argv[]) {
int a;
int b;
int c;
char buf[10];
int i;
struct pollfd ufds[1];
ufds[0].fd = 0;
ufds[0].events = POLLIN;
int rv;
int dummy;
for(i=0; i < 10; i++) {
printf("%i ", i);
if((rv = poll(ufds, 2, 3500)) == -1) perror("select");
else if (rv == 0) printf("Timeout occurred!\n");
else if (ufds[0].revents & POLLIN) {
printf("return hit\n");
read(0, buf, 10);
}
fflush(stdout);
}
return 0;
}
You are telling
pollyou have 2 file descriptors (2 pollfd structures) but you only have one. That’s undefined behavior (you’re tricking poll to tread into unallocated memory). Change that argument to 1.