Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Capture CTRL+C to avoid mem leak 1

Status
Not open for further replies.
Use a signal handler approach perhaps
Code:
#include <iostream>
#include <cstdlib>
#include <signal.h>
#include <windows.h>

class foo {
public:
    foo ( ) {
        std::cout << "ctor called" << std::endl;
    }
    ~foo ( ) {
        std::cout << "dtor called" << std::endl;
    }
};

volatile int ctrlc_pressed = 0;
void ctrlc_handler ( int sig ) {
    ctrlc_pressed = 1;
}

int main ( ) {
    signal( SIGINT, ctrlc_handler );
    foo *bar = new foo;
    std::cout << "Press ctrl-c to exit" << std::endl;
    while ( !ctrlc_pressed ) {
        std::cout << ".";
        std::cout.flush();
        Sleep(1000);
    }
    delete bar;
    system("pause");
    return 0;
}
Essentially, all the signal handler does is set a flag to indicate that ctrl-c was pressed. At some regular point in your code, you need to check that flag, and if set, perform an orderly exit from your program.

But bear this in mind when writing signal handlers in win32.
msdn said:
Note SIGINT is not supported for any Win32 application including Windows NT and Windows 95. When a CTRL+C interrupt occurs, Win32 operating systems generate a new thread to specifically handle that interrupt. This can cause a single-thread application such as UNIX, to become multithreaded, resulting in unexpected behavior.

--
 
Thanks Salem, that works for one case namely CTRL+C.
But what to do when pressing the X on the windows console?

Whatever you do will be insignificant, but it is very important that you do it.
(Mahatma Gandhi)
 
Correction, this should read:

Perhaps this is a better way of registering the handler in win32 console environments.



--
 
Now... Thats what I was looking for! Thank you verry much Salem.

Whatever you do will be insignificant, but it is very important that you do it.
(Mahatma Gandhi)
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top