Hey I was writing a udp client server in which a client waits for packets from server.But I want to limit this wait for certain time.After client don’t get response for a certain moment in raise an alarm,basically it comes out and start taking remedy steps.So what are the possible solution for it.I think writing a wrapper around recv will work but how exactly this has to be done,I mean how will make recv raise alarm for you after that time limit.
Any Help in this regard will be appreciated.
Thanks!
If you want to do socket communications with timeouts, then
selectis the way to go.You basically set up arrays of file descriptors for various events such as read-ready or write-able, then call
selectwith a timeout. If one of the events is valid, you will be notified and you can perform your actions.If none of the events occurs before the timeout, you’ll still be notified and can take whatever remedial action you see fit.
See here for the gory details, expanded on below.
Alternatively, you can use
setsockoptwith the SO_RCVTIMEO:For details on
select, you use theFD_ZEROandFD_SETmacros to construct a set of file descriptors (fdsets) of interest to you. You can have three sets, one indicating whether one or more fds has data to read, one indicating whether one or more is ready for writing to, and one indicating errors. You may not necessarily have all three, it depends on what your code is doing.Once you’ve set up the fdsets, you pass them, along with the number of fds and a timeout, to
selectwhich weaves its magic and returns to you. Before you do this, make a copy (FD_COPY) of the fdsets for later recovery.On return, there’s either been an error, timeout or an event pertaining to one of the fds of interest. In that latter case, the fdsets have been modified to only have the fds set for those with an event and you can use
FD_ISSETto detect which ones.Then, once you’ve handled all the events, use
FD_COPYto restore the original fdsets (they were modified byselect, remember) and callselectagain. Continue for as long as you need to.Keep in mind that an error return from
selectis not necessarily fatal. You can get (inerrno)EAGAINfor a temporary resource shortage orEINTRif a signal was handled. For that second case, you can just re-enter the select call. For the first, I’d implement a retry loop in case it was just a temporary thing.