在D程序退出前如何运行确定code/function?

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

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

你可能会逃脱这样的事情:

void main() {
    try {
        dostuff();
    } finally {
        printf("bye\n");
    };
};

finally 块将 运行 即使 dostuff() 抛出 ErrorThrowable。我不太熟悉标准 IO、控制台信号或其他任何东西,但至少试一试。

此外,即使 dostuff() 调用 Runtime.terminate() finally 块仍然会 运行。但是 abort() 却不是这样。

您可以使用 core.stdc.signal,它包含对 C header signal.h 的绑定。现在,如果这是 Windows,你可能 运行 变成一些 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
    }
}