Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I handle interrupt signal and call destructor in c++? [duplicate]

Possible Duplicate:
Is destructor called if SIGINT or SIGSTP issued?

My code like this:

#include <iostream>
#include <signal.h>
#include <cstdlib>

void handler(int) {
    std::cout << "will exit..." << std::endl;
    exit(0);
}

class A {
public:
    A() {std::cout << "constructor" << std::endl;}
    ~A() {std::cout << "destructor" << std::endl;}
};

int main(void) {
    signal(SIGINT, &handler);

    A a;
    for (;;);

    return 0;
}

When I pressed Ctrl-C, it printed:

constructor
^Cwill exit...

There is no "destructor" printed. So, how can I exit cleanly?

like image 627
大宝剑 Avatar asked Mar 08 '12 09:03

大宝剑


1 Answers

With difficulty. Already, the code you've written has undefined behavior; you're not allowed to output to a stream in a signal handler; for that matter, you're not allowed to call exit either. (I'm basing my assertions here on the Posix standard. In pure C++, all you're allowed to do is assign to a variable of sig_atomic_t type.)

In a simple case like your code, you could do something like:

sig_atomic_t stopFlag = 0;

void
handler( int )
{
    stopFlag = 1;
}

int
main()
{
    signal( SIGINT, &handler );
    A a;
    while ( stopFlag == 0 ) {
    }
    std::cout << "will exit..." << std::endl;
    return 0;
}

Depending on the application, you may be able to do something like this, checking the stopFlag at appropriate places. But generally, if you try this, there will be race conditions: you check stopFlag before starting an interuptable system call, then do the call; the signal arrives between the check and the call, you do the call, and it isn't interrupted. (I've used this technique, but in an application where the only interruptable system call was a socket read with a very short timeout.)

Typically, at least under Posix, you'll end up having to create a signal handling thread; this can then be used to cleanly shut down all of the other threads. Basically, you start by setting the signal mask to block all signals, then in the signal handling thread, once started, set it to accept the signals you're interested in and call sigwait(). This implies, however, that you do all of the usual actions necessary for a clean shutdown of the threads: the signal handling thread has to know about all other threads, call pthread_cancel on them, etc., and you're compiler has to generate the correct code to handle pthread_cancel, or you need to develop some other means of ensuring that all threads are correctly notified. (One would hope, today, that all compilers handle pthread_cancel correctly. But one never knows; doing so has significant runtime cost, and is not usually needed.)

like image 152
James Kanze Avatar answered Sep 28 '22 11:09

James Kanze