Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ - How to execute a command on application exit?

I am very new to C++ and have recently started a project for which I need to access a device, collect certain data and forward it to a datastream on a local network.

While my application does all the things require it lacks on function: When I close the window, in which the application is running it does not stop the hardware-device. The result is, that I have to do a hardware reset every time I am finished with the program. This is not only inconvienient but impossible for the programms intended usage.

I basically just want to set a callback for a function, that is executed, when the program is closed (either by clicking the x, pressing Alt-F4 etc.)

Is this possible? I the possibility to create a handler for such events:

BOOL WINAPI ConsoleHandler(DWORD dwCtrlEvent)
{
    switch (dwCtrlEvent)
    {
    case CTRL_CLOSE_EVENT:
        // something
    case CTRL_SHUTDOWN_EVENT:
        // the same?
    default:
        return FALSE;
    }
}

If this is a correct approach I am wondering how to use this handler? Do I need to create such a handler in my program and the update is constantly?

I am grateful for any help Jonas

like image 473
Jonidas Avatar asked Mar 04 '26 17:03

Jonidas


2 Answers

Proper RAII usage would help you in this case.

This basically says to wrap resource ownership inside of objects. You can then create an object on program start and clean any resources up on program end:

struct DeviceManager
{
     DeviceManager() { InitDevice(); }
     ~DeviceManager() { DecativateDevice(); }
};

DeviceManager dm;  //namespace scope, single translation unit

dm will be initialized on program start-up, before entry to main() and will be released on program end.

like image 139
Luchian Grigore Avatar answered Mar 06 '26 05:03

Luchian Grigore


There's a standard library function atexit, which allows you register a callback to be called when the program exits normally.

To handle abnormal termination, you can employ an exception handler. Simple try{}/catch{} block with the handling code in or after the catch{} should suffice for most simple programs. For advanced setup, refer to structured exception handling here.

like image 33
Hari Mahadevan Avatar answered Mar 06 '26 05:03

Hari Mahadevan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!