cserversignalstftp

How can I use SIGALRM to abort my server connection?


I am using fork() to implement a TFTP server right now. If my server does not hear from another party for 20s, how can I use SIGALRM to abort the connection?

Here is a part of my code:

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);
    }
}

Solution

  • Use alarm() to set the timer, once timer expired use sigaction() to handle the signal.

    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);
    

    Once handler is called, abort the server fd.

     static void handler(int sig) { 
                /* send the SIGABRT to server process  */  
    
     }