3

As far as I understand signals sent to a parent process should not be sent to children. So why does SIGINT reach both the child and the parent in the example below?

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

void sigCatcher( int );

int main ( void ) {
    if (signal(SIGINT, sigCatcher) == SIG_ERR) {
        fprintf(stderr, "Couldn't register signal handler\n");
        exit(1);
    }
    if(fork() == 0) {
        char *argv[] = {"find","/",".",NULL};
        execvp("find",argv);
    }
    for (;;) {
        sleep(10);
        write(STDOUT_FILENO, "W\n",3);
    }

    return 0;
}

void sigCatcher( int theSignal ) {
        write(STDOUT_FILENO, "C\n",3);
}
William Pursell
  • 204,365
  • 48
  • 270
  • 300
Ahtenus
  • 565
  • 6
  • 11
  • when you execute fork you make an exact duplicate of the process that ran the command, and since the signal method is executed before fork, both the child and the parent catch the signal. – Ionut Hulub Oct 15 '12 at 14:07
  • But exec replaces all the code so the signalhandler gets overwritten. – Ahtenus Oct 15 '12 at 14:21

1 Answers1

3

If you are sending SIGINT by typing ^-C, the signal is sent to all processes in the foreground processing group. If you use kill -2, it will only go to the parent (or whichever process you indicate.)

William Pursell
  • 204,365
  • 48
  • 270
  • 300