假设我有等待用户输入的循环.如果用户按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)