1

I used the following code while studying signals.

#include<stdio.h>
#include<sys/stat.h>
#include<sys/wait.h>
#include<unistd.h>
#include<stdlib.h>
#include<signal.h>
#include<sys/types.h>

int handler(int sig)
{
    printf("interrupt has been invoked\n");
}

int main(){
    pid_t pid;//pid_t is the datatype for process ids
    int status;

    signal(SIGINT,handler);
    if((pid=fork())==0)
    {
        while(1)
            sleep(1);
        exit(0);
    }
    else
    {
        wait(NULL);
    }
}

and the output received on using ctrl+c was this:

^Cinterrupt has been invoked
interrupt has been invoked
^Cinterrupt has been invoked
interrupt has been invoked
^Cinterrupt has been invoked
interrupt has been invoked

Can someone please explain why "interrupt has been invoked" is being printed twice every time ctrl+c is used?

1

This is because the signal handler is valid for both parent and child after the fork() call.

Since the forked child runs in the same process group as the parent, both processes receive the signal.

You may like to use this printf() command:

printf("interrupt has been invoked in pid %d\n", (int)getpid());

The tty driver has a tty process group set up and if you type ^C and ^C is set up as the TTY INTR character, then the tty driver sends SIGINT to all processes that are in the same process group as the tty driver.

  • but when the process group leader terminates,it sends the SIGHUP signal and not the SIGINT signal right? – dhruv gupta Jun 14 '18 at 12:43
  • he process group leader does not send signals unless it calls kill() or similar. SIGHUP is send by the tty driver in some cases. – schily Jun 14 '18 at 12:45

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.