Re: use alarm() to achieve timeout.

On Dec 17, 12:18 am, David Schwartz <dav...@xxxxxxxxxxxxx> wrote:
On Dec 15, 9:13 pm, guanghui <hellog...@xxxxxxx> wrote:

sorry, I think I forgot something.
the signal handler is registered with sa_flags |=SA_INTERRUPT;
and the following is the hander:
void sig_alrm(int signo)
return; /* just interrupt the recvfrom() */}

There's your bug. How do you know that will interrupt the 'recvfrom'?

and when data arrived before SIGALRM is generated , we simply
turn off the alarm using alarm(0);

what I really mean is "alarm( ) and recvfrom( )" should be an
atomic operation, when SIGALRM is generated and caught,
the program is blocked inside the recvfrom system call so
the handler would interrupt recvfrom( ).

You are correct, they should be atomic. However, your code doesn't
make them behave atomically, so your code is broken.

The correct fix is for the signal handler to *HANDLE* the signal, not
just ignore it. Handling the signal requires ensuring that the program
control flow does not go the wrong way.


Thanks for your reply. So you mean what I concern is right and the
implementation of timeout using alarm() from
UNP(<<unix network programming ,3rd, by Richard stevens>>)
is not perfect(the code I wrote above is from UNP)
just because of the small window between alarm() and recvfrom().
then could you please show me a correct solution to implement
timeout using alarm() when doing socket i/o?