I have a sender and a receiver connected with sockets. When the sender sends something, i would like to use the timer on poll() to know if no acknowledgement is coming back from the receiver. After reading a lot of questions (Why does poll keep returning although there is no input?, Embedded Linux poll() returns constantly, poll(2) doesn't empty the event queue) i understand that the poll() function can return 1 even if the receiver didn't send anything back, just because the read() function would not block on the file descriptor of the socket.
But i would like to use the timeout of poll() to know if nothing arrived on the socket. How can i make the poll() function return 1 only if new data has arrived on the socket ?
Here is a sample of my code, in case i'm doing something wrong:
while(1){
rv = poll(ufds, ufds[0].fd +1 , 1000);
if (rv == -1) {
perror("poll");
} else if (rv == 0) {
printf("Timeout occurred! No data after 1 seconds.\n");
} else {
if (ufds[0].revents & POLLIN) {
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)
{
die("recvfrom()");
}
printf("ACK = %s \n", buf);
}
if (ufds[0].revents & POLLPRI) {
if (recvfrom(s, buf, BUFLEN, 0, (struct sockaddr *) &si_other, &slen) == -1)
{
die("recvfrom()");
}
}
}
}
TL;DR: this code never prints "Timeout occurred!" because the file descriptor of the socket is always ready. Can i change this behavior ?
thanks a lot !