Using signals in c

Asked by At

I was writing a simple program in c where via fork i create i child process:

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

int handler(){

}
int main(int argc, char **argv)
{

    pid_t c=fork();
    if(c>0){
        sleep(1);
        printf("f:pid is %d \n",getpid());
        kill(c,SIGINT);
        wait(NULL);
    }

    if(c==0){
        pause();
        signal(SIGINT,handler);
        printf("child:pid is %d \n",getpid());
    }
}

The problem is that the child prints nothing. I thought that pause just waits for a signal to unpause the process and i can't understand why the print never happens.Any ideas?

1 Answers

4
Barmar On

You need to set up the handler before you pause. Otherwise, pause() will be interrupted by the signal, then the default action of the signal will be taken, which is to terminate the process. It will never add the handler because the process is killed first.

    if(c==0){
        signal(SIGINT,handler);
        pause();
        printf("child:pid is %d \n",getpid());
    }