scope(exit) and Ctrl-C

kdevel kdevel at vogtner.de
Sat Dec 2 01:30:05 UTC 2017


On Saturday, 2 December 2017 at 00:41:19 UTC, Wanderer wrote:
> I wonder why `scope(exit)` code is not executed when the 
> program is terminated with Ctrl-C.

Which OS?

> 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?

It's normal. Ctrl-C (under UNIX, Linux) sends SIGINT to the 
process. There are two options:

    1. Handle this interrupt in your programm (But then: What 
about Ctrl-\ and
       SIQUIT)?

    2. Prevent the generation of SIGINT: Put the terminal into raw 
mode [1]

> Is there any method to cleanup on Ctrl-C?

Yes. Take option 1. or option 2.

[1] https://linux.die.net/man/3/cbreak

"The raw and noraw routines place the terminal into or out of raw 
mode. Raw mode is similar to cbreak mode, in that characters 
typed are immediately passed through to the user program. The 
differences are that in raw mode, the interrupt, quit, suspend, 
and flow control characters are all passed through uninterpreted, 
instead of generating a signal. The behavior of the BREAK key 
depends on other bits in the tty driver that are not set by 
curses."


More information about the Digitalmars-d-learn mailing list