Catching SIGTERM in C

15,687

Works fine:

> cat > sig.c    # paste your code
> gcc sig.c
> ./a.out &
[1] 20549
PID is 20549  and Parent is 15574
PID is 20549  and Parent is 15574
> kill 20549
Caught!
Loop run was interrupted with 1 sec to go, finishing...
> Finished loop run 0.
done.
>
[1]    Done                          ./a.out
Share:
15,687
user2466886
Author by

user2466886

Updated on June 07, 2022

Comments

  • user2466886
    user2466886 almost 2 years

    I'm trying to learn how to catch sigterm for a larger assignment I have in class. I'm following the steps in this tutorial however it doesn't work for me. When I enter the command "kill [process id]" the sleep doesn't stop and just continues. I've tried kill both the child and parent IDs and nothing happens. Any ideas? Here's what I have:

    #include <signal.h>
    #include <stdio.h>
    #include <string.h>
    #include <unistd.h>
    
    volatile sig_atomic_t done = 0;
    
    void term(int signum)
    {
       printf("Caught!\n");
       done = 1;
    }
    
    int main(int argc, char *argv[])
    {
        struct sigaction action;
        memset(&action, 0, sizeof(action));
        action.sa_handler = term;
        sigaction(SIGTERM, &action, NULL);
    
        int pid = getpid();
        int parentID = getppid();
        printf("PID is %d  and Parent is %d \n",pid, parentID);
    
        int loop = 0;
        while (!done)
        {
            printf("PID is %d  and Parent is %d \n",pid, parentID);
            int t = sleep(10);
            /* sleep returns the number of seconds left if
             * interrupted */
            while (t > 0)
            {
                printf("Loop run was interrupted with %d "
                       "sec to go, finishing...\n", t);
                t = sleep(t);
            }
            printf("Finished loop run %d.\n", loop++);
        }
    
        printf("done.\n");
        return 0;
    }