Strange output when using fork() and signal handling

375 views Asked by At
#include<stdio.h>
#include<stdlib.h>
#include<signal.h>
#include<unistd.h>
#include<sys/types.h>

void sighup()
{
    signal(SIGHUP,sighup);
    printf("Received SIGHUP! Happy Now ??\n");
}

void sigbus()
{
    signal(SIGBUS,sigbus);
    printf("received SIGBUS! Get a life dude !\n");
}

void sigquit()
{
    printf("I am done with you. Bye!!\n");
    fflush(stdout);
    exit(0);
}

int main()
{   
    int pid = fork();

    if (pid < 0)
    {
        perror("fork");
        exit(1);
    }

    if (pid == 0)
    {   
        printf("child\n");

        signal(SIGHUP,sighup);
        signal(SIGBUS,sigbus);
        signal(SIGQUIT,sigquit);
        while(1)
        {
            ;
        }
    }
    else
    {
        printf("parent\n");
        kill(pid, SIGHUP);
        kill(pid, SIGBUS);
        kill(pid, SIGQUIT);

        wait();
    }
}

I wrote this program as part of assignment on signal handling but the output of the program is kind of weird.

The output of the program is ::

parent

ideone link :: http://ideone.com/a1DCik

I have no clue how this can be the output. It seems the child process is not being created.

Please explain the output.

1

There are 1 answers

4
Kerrek SB On BEST ANSWER

There is no synchronization between your two processes. It's entirely conceivable that the child process receives an unhandled signal and dies before it gets to execute any of its signal calls.

In fact, that's extremely likely: The parent process continues execution immediately after the fork() and performs the kills, while the child process first needs to be created and scheduled. Both of those take a very long time compared to the kill calls in the parent, and if you're on a single-core machine, you'd have to be very lucky if you wanted to see the parent be suspended before it gets to the kill() line.