We often encounter problems with setting timeouts for blocking operations, such as blocking sockets read Read setting 10-second timeout, one of which is to call the alarm function, which generates a SIGALRM signal during the specified time-out period, causing the blocking operation to break.
But the disadvantage is:
1, may interfere with the existing alarm calls in the process, such as timer, SetTimer, sleep and so on.
2. It is very difficult to use the signal correctly in a multithreaded program, so it is recommended to use this technique only in non-threaded or single-threaded programs.
Demo program (Linux Environment):
#include <stdio.h> #include <netinet/in.h>//for struct sockaddr_in #include <string.h>//for memset #
Include <signal.h>//for signal typedef void (*sighandler_t) (int);
static void Read_alarm (int signo) {return;}
int main () {int conn_sock;
struct sockaddr_in ser_addr;
int ret;
Char buf[1024];
sighandler_t Src_sig;
struct Sigaction sa_alarm;
Conn_sock = socket (af_inet, sock_stream, 0);
if (Conn_sock < 0) {perror ("socket error");
return-1;
} memset (&ser_addr, 0, sizeof (SER_ADDR));
ser_addr.sin_family = af_inet;
Ser_addr.sin_port = htons (135);
Inet_pton (Af_inet, "127.0.0.1", &ser_addr.sin_addr);
ret = Connect (conn_sock, (struct sockaddr *) &ser_addr, sizeof (SER_ADDR));
if (Ret < 0) {perror ("connect error");
return-1;
}//src_sig = Signal (SIGALRM, read_alarm);
Sa_alarm.sa_flags = Sa_resethand; Sa_alarm.sa_handler = Read_Alarm
Sigaction (SIGALRM, &sa_alarm, NULL);
Alarm (10);
ret = Read (Conn_sock, buf, sizeof (BUF));
if (Ret < 0) {perror ("read error");
} else if (ret = = 0) {printf ("Close by peer\n");
} else {printf ("recv%d bytes\n", ret);
} alarm (0);
Signal (SIGALRM, src_sig);
return 0;
}
Operation Result:
Read error:interrupted system call
Using the signal function in a Linux system, the read timeout will not be interrupted after 10 seconds because the interrupted read will be restarted automatically after the interrupt.
The Segaction function is required to verify that when read exceeds 10 seconds, alarm emits a SIGALRM signal and read is interrupted.