socket
Table of Contents
connect
- If
connect()
fails, the state of the socket is unspecified.
EINTR
- POSIX specification defines that when signal (such as
Ctrl+C
) is caught,recv
returnsEINTR
error. - When
Ctrl+C
is pressed in this case,- signal handler is executed, 'stop' is set to 1,
recv
returnsEINTR
- Using
SA_RESTART
within the signal handler, it's possible to make the functions not returnEINTR
and just retry.
volatile int stop = 0;
void handler (int)
{
stop = 1;
}
void event_loop (int sock)
{
signal (SIGINT, handler);
while (1) {
if (stop) {
printf ("do cleanup\n");
return;
}
/* What if signal handler is executed at this point?
This may be a problem, or not.
*/
char buf [1];
int rc = recv (sock, buf, 1, 0);
if (rc == -1 && errno == EINTR)
continue;
printf ("perform an action\n");
}
}