How can I programmatically get the default behavior of sigterm inside a custom signal handler?

情到浓时终转凉″ 提交于 2019-12-11 07:16:00

问题


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:

  1. The code as-is will print Constructing! but not Dying! if SIGTERM is received.
  2. When the //signal line is commented back in, and exit(0) is commented back in, the code will print both Constructing! and Dying!
  3. When exit(0) is commented out, and abort() is commented in, the program will output Constructing! followed by Aborted (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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!