我如何使用 SIGALRM 中止我的服务器连接?
How can I use SIGALRM to abort my server connection?
我现在正在使用 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);
}
}
使用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 */
}
我现在正在使用 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);
}
}
使用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 */
}