0

I'm running this piece of code several times (for a non-blocking recvfrom on a UDP socket):

struct timeval read_timeout;
read_timeout.tv_sec = 0;
read_timeout.tv_usec = 1000;
setsockopt(sockfd, SOL_SOCKET, SO_RCVTIMEO, &read_timeout, sizeof read_timeout);
ssize_t n = recvfrom(sockfd, recvline, sizeof(recvline), 0, NULL, NULL);
if (n < 0) {
    perror("recvfrom");
    return -1;
} else // ... normal usage

Sometimes the program stops and I get the following error from perror

recvfrom: Resource temporarily unavailable

What could the issue be?

ikegami
  • 367,544
  • 15
  • 269
  • 518
Robb1
  • 4,587
  • 6
  • 31
  • 60
  • @EugeneSh. thanks for your answer. I understand what the problem is, but how can I solve it? Can I ignore this problem and loop with recvfrom again? – Robb1 Jan 17 '18 at 16:43
  • Increase the timeout or make it completely blocking (if possible). – Eugene Sh. Jan 17 '18 at 16:48
  • @ikegami that means that actually I didn't understand the problem! I thought that using `setsockopt()` in such a way would simply let me skip the `recvfrom` if I wasn't receiving anything and go on with the following code... not making it return with an error! – Robb1 Jan 17 '18 at 17:08
  • Comments are not for new questions. Existing questions are not for new questions. If you have a question to ask, click [Ask Question](https://stackoverflow.com/questions/ask). – ikegami Jan 17 '18 at 20:44

1 Answers1

1

Just modify the code to do what you want. When you get an error, instead of calling perror unconditionally, check if it's a timeout. If it's not a timeout, then call perror and return. If it's a timeout, do whatever it is you want to do when you get a timeout.

David Schwartz
  • 179,497
  • 17
  • 214
  • 278