如果SIGINT或SIGSTP发出,是析构函数吗? [英] Is destructor called if SIGINT or SIGSTP issued?

查看:600
本文介绍了如果SIGINT或SIGSTP发出,是析构函数吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类有一个用户定义的析构函数。如果该类最初被实例化,然后在程序运行时发出SIGINT(使用CTRL + C在UNIX中),析构函数是否会被调用?对于SIGSTP(unix中的CTRL + Z)的行为是什么?

I have a class with a user-defined destructor. If the class was instantiated initially, and then SIGINT is issued (using CTRL+C in unix) while the program is running, will the destructor be called? What is the behaviour for SIGSTP (CTRL + Z in unix)?

推荐答案

但是,您可以轻松更改大多数信号的默认行为。

However, you can easily change the default behavior for most signals.

代码显示如何使信号正常退出你的程序,包括调用所有通常的析构函数:

This code shows how to make a signal exit your program normally, including calling all the usual destructors:

#include <iostream>
#include <signal.h>
#include <cstring>
#include <atomic>

std::atomic<bool> quit = false;    // signal flag

void got_signal(int)
{
    quit = true;
}

class Foo
{
public:
    ~Foo() { std::cout << "destructor\n"; }
};

int main(void)
{
    struct sigaction sa;
    memset( &sa, 0, sizeof(sa) );
    sa.sa_handler = got_signal;
    sigfillset(&sa.sa_mask);
    sigaction(SIGINT,&sa,NULL);

    Foo foo;    // needs destruction before exit
    while (true)
    {
        // do real work here...
        sleep(1);
        if( quit ) break;    // exit normally after SIGINT
    }
    return 0;
}

如果运行这个程序并按下control-C, 析构函数打印。请注意,你的信号处理函数(got_signal)应该很少做任何工作,除了设置一个标志和安静地返回,除非你真的知道你在做什么。

If you run this program and press control-C, you should see the word "destructor" printed. Be aware that your signal handler functions (got_signal) should rarely do any work, other than setting a flag and returning quietly, unless you really know what you are doing.

信号是可以收集的,如上所示,但不是SIGKILL,你没有控制它,因为SIGKILL是一个最后一道方法,用于杀死失控的进程,而不是SIGSTOP允许用户冻结进程冷。注意,如果需要你可以捕获SIGTSTP(control-Z),但是你不需要,如果你唯一对信号的兴趣是析构函数行为,因为最终在控制Z之后,进程将被唤醒,将继续运行,将正常退出,所有析构函数都有效。

Most signals are catchable as shown above, but not SIGKILL, you have no control over it because SIGKILL is a last-ditch method for killing a runaway process, and not SIGSTOP which allows a user to freeze a process cold. Note that you can catch SIGTSTP (control-Z) if desired, but you don't need to if your only interest in signals is destructor behavior, because eventually after a control-Z the process will be woken up, will continue running, and will exit normally with all the destructors in effect.

这篇关于如果SIGINT或SIGSTP发出,是析构函数吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆