scope(exit) and Ctrl-C
Ali Çehreli
acehreli at yahoo.com
Sat Dec 2 01:17:18 UTC 2017
On 12/01/2017 04:41 PM, Wanderer wrote:
> I wonder why `scope(exit)` code is not executed when the program is
> terminated with Ctrl-C.
>
> For example:
>
> ```
> import std.stdio;
> import core.thread;
>
> void main()
> {
> scope (exit)
> {
> writeln("Cleanup");
> }
> writeln("Waiting...");
> Thread.sleep(10.seconds);
> writeln("Done waiting...");
> }
> ```
>
> If I wait 10 seconds, I get "Cleanup" output.
> But if I use Ctrl-C to terminate the program before 10 seconds elapse,
> there's no "Cleanup" output.
>
> Is it intentional?
> Is there any method to cleanup on Ctrl-C?
Combined your code with this solution:
http://forum.dlang.org/post/isawmurvxjyldcwddsfj@forum.dlang.org
import core.thread;
import std.stdio;
import core.sys.posix.signal;
// Note: This one is thread-local; make shared or __gshared if needed
bool doQuit;
extern(C) void handler(int num) nothrow @nogc @system
{
printf("Caught signal %d\n",num);
doQuit = true;
}
void main(string[] args)
{
signal(SIGINT, &handler);
scope (exit)
{
writeln("Cleanup");
}
writeln("Waiting...");
foreach (_; 0 .. 100) {
Thread.sleep(100.msecs);
if (doQuit) {
break;
}
}
writeln("Done waiting...");
}
Ali
More information about the Digitalmars-d-learn
mailing list