Different signal handlers for parent and child
Asked Answered
P

1

10

I have a program with a signal handler:

signal(SIGINT, signalhandler);

Then the program forks and the child needs a different signal handler so:

pid = fork();

/* What happens here? */

if(pid==0)
{
signal(SIGINT, signalhandler_for_child);
}

So what happens if a SIGINT is called right after the fork but before the new sign handler is assigned?

Can this happen or there is no possibility to be interrupted before the child gets the new signal handler.

If it is possible. How could I queue the signal to the child so it gets time to get the new handler?

I know that the probabilities, if they exist, must be almost 0, but I want to make sure the application is robust in this aspect.

Pvc answered 21/3, 2018 at 10:35 Comment(2)
Block all signals before fork, then set appropriate masks for both?Laevogyrate
Yes, I was not aware that blocking signals mean to actually queue them. I thought blocked signals were discarded later on. Thanks.Pvc
R
11

So what happens if a SIGINT is called right after the fork but before the new sign handler is assigned?

The signal handler installed in the parent will be called. Child process inherits it.

Can this happen or there is no possibility to be interrupted before the child gets the new signal handler.

Cetainly can happen.

If it is possible. How could I queue the signal to the child so it gets time to get the new handler?

To ensure, you need to block SIGINT before calling fork() and then reinstall a different for SIGINT in the child process and then unblock SGINT.

/* block SIGINT here. */

pid = fork();

if (pid == 0) {
    /* Install a new SIGINT handler here. */
    /* Unblock SIGINT. */
    ...
} else if (pid > 0) {
   /* The SIGINT handler is already in place. So just unblock SIGINT. */
   ...
} else {
   /* error */
}

Look at sigprocmask() and pthread_sigmask() for blocking and unblocking signals.

You may also find the GNU documentation on signal blocking useful.

Reddy answered 21/3, 2018 at 10:54 Comment(3)
Thanks for your answer. However, if I block the SIGINT, and one of these signals occurs when the signal is blocked, the process (or processes if it is after fork) will not have any behaviour and they will not know they need to exit. In this case, I would need to modify the process who is sending the signals to send the same signal several times and I find this a bit "dirty" solution. Would there be another possibility?Pvc
Any signal received when it's blocked will be delivered once you unblock them. There's nothing dirty about this - it's the sort of the "standard" way.Reddy
Thank you. This is the key of my issue. I was not aware that blocked signals are actually queued. I thought they were just blocked and then discarded.Pvc

© 2022 - 2024 — McMap. All rights reserved.