c - 我如何使用 SIGALRM 中止我的服务器连接?

标签 c server signals tftp

我现在正在使用 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  */  

 }

关于c - 我如何使用 SIGALRM 中止我的服务器连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48918085/

相关文章:

c++ - posix信号 react 时间

c++ - OpenSSL 和信号

C - 在 R Holt-Winters 函数中调用的 C_Holt-Winters 函数

c - 将字符串的地址存储在字符串数组中

c - ISO C90 禁止在 C 中混合声明和代码

dart - 如何在 Google Compute Engine (GCE) 中安装 Dart?

iOS 应用程序由于无限 while 循环而无法渲染

c++ - 使用 C++ 在 ffmpeg 中解码为特定像素格式

node.js - 多个 Nodejs 服务器还是单个?

Linux 信号和中断处理程序