1

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);
    }
}
Undo
  • 25,519
  • 37
  • 106
  • 129

1 Answers1

0

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  */  

 }
Achal
  • 11,821
  • 2
  • 15
  • 37
  • what should i do in the handler function? – Haotian Song Feb 22 '18 at 01:32
  • send the signal to server using `kill` as `kill(SIGABRT,server_pid);` – Achal Feb 22 '18 at 01:33
  • I am getting a seg fault after 20s on my server terminal, is that what kill does? – Haotian Song Feb 22 '18 at 01:50
  • @HaotianSong yes, because when server receives SIGABRT, by default action of signal SIGABRT will be performed which is `SIGABRT 6 Core Abort signal from abort(3)` it will generate core dump & seg. fault – Achal Feb 22 '18 at 02:44
  • @HaotianSong What you want to don in server once server receives the signal ? are you just want to indicate to the server that I'm not receiving data after 20s ? Tell me exact requirement. – Achal Feb 22 '18 at 02:46