Search code examples
dexitexit-code

How do I run certain code/function before the program exits in D?


Suppose I have loop which awaits for user input. If user presses Ctrl+C the program exits normally. However, I'd like to do a couple of things before exit. Is it possible to run a function once Ctrl+C was pressed and program is about to exit?


Solution

  • You could use core.stdc.signal, which contains bindings to the C header signal.h. Now, if this is for Windows, you might run into some problems:

    SIGINT is not supported for any Win32 application. When a CTRL+Cinterrupt occurs, Win32 operating systems generate a new thread to specifically handle that interrupt. This can cause a single-thread application, such as one in UNIX, to become multithreaded and cause unexpected behavior.

    __gshared bool running = true;
    extern(C) void handleInterrupt(int) nothrow @nogc
    {
        running = false;
    }
    
    void main()
    {
        import core.stdc.signal;
        signal(SIGINT, &handleInterrupt);
    
        scope(exit)
        {
            //Cleanup
            import std.stdio : writeln;
            writeln("Done");
        }
    
        while(running)
        {
            //Do some work
        }
    }