我正在使用fork()来实现TFTP服务器。如果我的服务器在20秒内没有收到另一方的消息,我该如何使用SIGALRM
中止连接?
以下是我的代码的一部分:
while (1)
{
pid = fork();
if ( pid == -1 )
{
return EXIT_FAILURE;
}
if ( pid > 0 )
{
wait(NULL);
close(server_socket);
}
else
{
do
{
n = recvfrom(server_socket, buffer, BUF_LEN, 0,
(struct sockaddr *)&sock_info, &sockaddr_len);
}while(n > 0);
}
}
答案 0 :(得分:0)
使用alarm()
设置计时器,一旦计时器到期,使用sigaction()
来处理信号。
do
{
struct sigaction s;
s.sa_handler = handler; /* Establish the signal handler */
sigemptyset(&s.sa_mask);
s.sa_flags = 0;
alarm(20); /* first set the alarm of 20s */
/* if within 20s server doesn't receive anthing, handler will be evoked */
sigaction(SIGALRM, &s, NULL); /* when timer expires, handler will be called */
n = recvfrom(server_socket, buffer, BUF_LEN, 0,
(struct sockaddr *)&sock_info, &sockaddr_len);
}while(n > 0);
调用处理程序后,中止服务器fd。
static void handler(int sig) {
/* send the SIGABRT to server process */
}