问题
Based on man -S 7 signal
, when a program which has not defined a signal handler receives SIGTERM
, the default action is to Term
.
I am registering a custom signal handler for SIGTERM
, but I want the final statement (after specific cleanup is done) in my custom handler to be a function call that achieves the exact same effect as Term
.
What is the correct function to call here?
I have tried exit(0)
, but that causes the destructors of statically initialized objects to be called, which does not match the behavior of Term
. I have also tried abort()
, and that causes a core dump.
In the following example, I am using the lifetime of statically allocated objects as an illustrative example, but my question is more broad than just the lifetime of statically allocated objects.
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
struct Foo{
~Foo() {
fprintf(stderr, "Dying!\n");
}
Foo() {
fprintf(stderr, "Constructing!\n");
}
};
Foo foo;
void sig_handler(int signo) {
// exit(0);
// abort();
}
int main(){
// signal(SIGTERM, sig_handler);
while(1);
}
Here are various behaviors:
- The code as-is will print
Constructing!
but notDying!
ifSIGTERM
is received. - When the
//signal
line is commented back in, andexit(0)
is commented back in, the code will print bothConstructing!
andDying!
- When
exit(0)
is commented out, andabort()
is commented in, the program will outputConstructing!
followed byAborted (core dumped)
.
To ask my question in another way, I want to know what I need to put in the body of signal_handler
in order to mimic behavior 1 in every way (not just the output I have shown).
回答1:
signal(SIGTERM, SIG_DFL);
kill(getpid(), SIGTERM);
There is no function call, as termination upon signals is handled by the kernel, not the user process, but this will restore the default handler, then send a signal to yourself, which kills the process just like the signal had never been caught.
回答2:
You can call _exit
instead of exit
, which should exit the process without running global destructors.
来源:https://stackoverflow.com/questions/22001667/how-can-i-programmatically-get-the-default-behavior-of-sigterm-inside-a-custom-s