🗄️Signal Handlers

In this section we shall see how to bind signal handlers to processes

signals.c
#include <stdio.h>
#include <signal.h>
#include <unistd.h>

// signal handler
void signalHandler(int sigint){
    printf("Process executed with code %d\n", sigint);
}

int main(){
    int id1 = fork();
    if(id1 != 0){
        int id2 = fork();

        // main thread
        if(id2 != 0){
            int wpid = wait(NULL);
            printf("Waiting for process %d to finish\n",wpid);
        }else{
            // this is child process 2
            signal(SIGINT, signalHandler);  // binding the signal handler to SIGINT signal

            int pid = getpid();
            printf("PID of child-process-2 : %d\n",pid);

            if(kill(pid, SIGINT) == -1)
                printf("Failed to terminate process %d",pid);
        }
    }else{
        // this is child process 1
        signal(SIGINT, signalHandler);  // binding the signal handler to SIGINT signal

        int pid = getpid();
            printf("PID of child-process-1 : %d\n",pid);

        if(kill(pid, SIGINT) == -1)
            printf("Failed to terminate process %d",pid);
    }
    return 0;
}

Output

PID of child-process-2 : 12391
Process executed with code 2
PID of child-process-1 : 12390
Process executed with code 2
Waiting for process 12391 to finish

Last updated