How to execute cleanup code on Ctrl-C (Break)?

Jonathan M Davis jmdavisProg at gmx.com
Sun Jul 8 18:46:28 PDT 2012


On Monday, July 09, 2012 03:31:52 Paul Dufresne wrote:
> Well, I was looking the documentation and not finding how to
> catch signals.
> 
> I thought, hey, does Windows have Posix signals?
> And the answer seems to be that Windows conform to Posix.1 (which
> is old, but does define signals)... after all, the code I want to
> translate does run in MinGW.
> 
> So, I search back this list... and the answer I am following
> right now, is
> 
> "That module is part of druntime, and you can import it with
>   import core.sys.posix.signal;
> 
>   The documentation isn't on dlang.org, probably because dlang.org
>   doesn't contain the documentation for OS-specific modules (it's
> hard
>   to generate the documentation for those when you're not on the
> same
>   OS).
> 
> So I am now reading this file on my installation:
> C:\dmd2\src\druntime\import\core\sys\posix\signal.di

With POSIX signal handling, you do whatever cleanup you do in the signal 
handler and that's it. You can make it so that the signal is ignored, I 
believe, but if it's a -9, then you can't (and in that case, I'm not even sure 
that you get to handle it). Normally, you let the OS kill your program after 
you've done whatever handling you do in your signal handler, in which case 
there is no graceful shutdown. But if you want a graceful shutdown, you may be 
able to have your signal handler eat the kill signal and then tell all of the 
threads in your program to shutdown, in which case, they would each have to 
handle shutting themselves down gracefully. And unless you have all of your 
threads keep checking a shared global variable which indicates that they 
should shutdown or (preferrably) you're using std.concurrency and each thread 
is watching for messages to shutdown, there's no way to get the threads to 
shutdown gracefully. You can't do anything like have all of your threads 
suddenly throw exceptions from wherever they are.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list