C – Why do we call Signal Handler twice?

Why do we call Signal Handler twice?… here is a solution to the problem.

Why do we call Signal Handler twice?

I am a newbie and work with signals in C. I’m analyzing the signal processing code extracted from a specific resource below.

Here is the code.

    #include <stdio.h>
    #include <signal.h>

void intproc();
    void quitproc();

main()
    {
      int i;

signal(SIGINT,intproc);
      signal(SIGQUIT,quitproc);

printf("Ctrl+c is disabled. Use ctrl+\\ to quit\n");

for (i=0;; i++) {
        printf("In an infinite loop...\n"); 
        sleep(200);
        }
    }

void intproc()
    {
      signal(SIGINT,intproc);
      printf("You have pressed ctrl+c.\n");
    }

void quitproc()
    { signal(SIGQUIT,intproc);
      printf("You have pressed ctrl+\\. Now the program quits.\n");
      exit(0);
    }

What I’m wondering is why do we call the signal handler “(SIGINT,intproc)” again in the intproc() function?

I tried running this code without a signal handler in that function and it works fine too.

Solution

This is very old code. In the old days (probably SunOS3, 1990s), signal handlers were automatically unloaded when executed. See signal(2) (the difference between SysV and BSD behavior) and avoid signal.

Read carefullysignal(7) and use sigaction(2). Care about asynchronous signal-safe functions (the only functions that can be called from signal handlers; You should not use printf!) in your signal handler. Consider simply setting some volatile sig_atomic_t global (or static) variables in the signal handler (and testing them externally).

Read Advanced Linux Programming, which explains these things in detail.

Related Problems and Solutions