问题
I am writing a system-critical program for a Linux distribution that I am developing. It needs to restart itself on receiving certain signals, to try to avoid crashing. The problem is, after the restart, I cannot re-enable that signal. That is, the signal cannot be received twice. After execv()'ing itself, when the new process calls signal() to set up the signal, SIG_DFL is returned. Every time. Even if I call it twice in a row -- indicating that it was never set in the first place. Is some weird flag being carried over from the original process?
回答1:
You are falling foul of the fact that you are essentially trying to recursively handle a signal.
When using signal()
to register a signal handler, that signal number is blocked until the signal handler returns - in effect the kernel / libc blocks that signal number when the signal handler is invoked, and unblocks it after the signal handler returns. As you never return from the signal handler (instead you execl
a new binary), SIGUSR1
stays blocked and so isn't caught the 2nd time.
This can be seen by examining /proc/</pid>/status
before and after you send the first SIGUSR1
.
Before:
$ cat /proc/<pid>/status | grep -E "Sig(Cgt|Blk)"
SigBlk: 0000000000000000
SigCgt: 0000000000000200
After:
$ cat /proc/<pid>/status | grep -E "Sig(Cgt|Blk)"
SigBlk: 0000000000000200
SigCgt: 0000000000000200
Note that SigCgt
indicates signal 10 is registered (the number is a bitfield; 10th bit is set, which equates to SIGUSR1, see man signal(7)
for the numbers). SigBlk
is empty before SIGUSR
is sent to your process, but after sending the signal it contains SIGUSR1
.
You have two ways to solve this:
a). Manually unblock SIGUSR
before calling execl
in sighandler
:
sigset_t sigs;
sigprocmask(0, 0, &sigs);
sigdelset(&sigs, SIGUSR1);
sigprocmask(SIG_SETMASK, &sigs);
b). Use sigaction
with the SA_NODEFER
flag instead of signal
to register the signal handler. This will prevent SIGUSR1
from being blocked inside the signal handler:
struct sigaction act;
act.sa_handler = signalhandler;
act.sa_mask = 0;
act.sa_flags = SA_NODEFER;
sigaction(SIGUSR1, &act, 0);
回答2:
Signal handlers aren't inherited across exec
because exec
overwrites your whole address space, and any signal handlers that aren't reset would then be pointing to the wrong place. The only time it's not reset is if it's set to, say, SIG_IGN
, which is not dependent on the address space of the pre-exec
process.
来源:https://stackoverflow.com/questions/1023955/signals-dont-re-enable-properly-across-execv