如何在程序退出D之前运行某些代码/功能?

sni*_*tko 1 d exit-code exit

假设我有等待用户输入的循环.如果用户按Ctrl + C,程序将正常退出.但是,在退出之前我想做几件事.一旦按下Ctrl + C并且程序即将退出,是否可以运行一个功能?

小智 5

您可以使用core.stdc.signal,其中包含与C头的绑定signal.h.现在,如果这是针对Windows的,您可能会遇到一些问题:

任何Win32应用程序都不支持SIGINT.当发生CTRL + Cinterrupt时,Win32操作系统会生成一个新线程来专门处理该中断.这可能导致单线程应用程序(例如UNIX中的应用程序)变为多线程并导致意外行为.

__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
    }
}
Run Code Online (Sandbox Code Playgroud)

  • http://stackoverflow.com/questions/16826097/equivalent-to-sigint-posix-signal-for-catching-ctrlc-under-windows-mingw显示了如何在Windows上执行此操作.好的答案顺便说一下! (2认同)