Question

Usually when your C program catches a SIGSEGV signal and there's no handler installed the standard C library will print "Segmentation fault" and kill the process afterwards. This is very useful in certain situation.

However, this behaviour changes after a fork() system call: For the parent everything stays as usual but the child will never print these messages. Why is that so and can it be restored to the default for the child?

Here's a minimal example:

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

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

    if (pid < 0) { return 1; }
    raise(SIGSEGV);

    return 0;
}

The output is Segmentation fault whereas I would expect two such messages.

Was it helpful?

Solution

The message isn't printed by the library, it's printed by the shell. Processes are only notified when one of their own child processes exits. After a fork, the new process is a grandchild of the shell, so the shell doesn't know about it and doesn't print anything when it exits due to a signal.

When a child exits, the parent process is sent a SIGCHLD signal. It can then use one of the wait() family of system calls to get the child's termination status and the signal that killed it.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top