kill signal example
Your code has a major race condition. You do not ensure that the child has finished calling signal
before the parent sends the signals. You either need to use some kind of synchronization primitive to make the parent wait for the child to install the handlers, or you need to install the signal handlers before forking so the child inherits them.
Here's the easiest way I know to synchronize processes like this:
- Before forking, call
pipe(p)
to create a pipe. fork()
.- In the parent,
close(p[1]);
(the writing end) andread(p[0], &dummy, 1);
- In the child,
close(p[0]);
andclose(p[1]);
after installing the signal handlers. - When the parent returns from
read
, you can be sure the child has setup its signal handlers. You can alsoclose(p[0]);
in the parent at this point.
Edit 2: Perhaps a better and easier approach:
- Before forking, call
sigprocmask
to block all signals and save the old signal mask. - In the parent, call
sigprocmask
again right after forking to restore the original signal mask. - In the child, call
sigprocmask
right after installing the signal handlers to restore the original signal mask.