3

D's (rather sparse) official documentation doesn't have anything about handling system signals on *nx or Windows.

The system module only has Endian and OS, syserror is deprecated / only for Windows errortext, and signals is about message-passing, not system signals.

Is there a way (in pure D) to install a signal handler, to capture and allow me to react to certain signals at runtime, or, at least a way to detect that a signal was recieved and an exception I can catch?

i.e, in Python, a simple example is:

import signal
signal.signal(signal.SIGSEGV, myFunctionToHandleSEGV)
# ...
Max Alibaev
  • 681
  • 7
  • 17
cat
  • 3,888
  • 5
  • 32
  • 61

1 Answers1

5

It is the same as in C, just with an import instead of an include. Find a C example that looks interesting to you, then change #include<signal.h> to import core.stdc.signal; if you are using just the standard C signal function, or import core.sys.posix.signal; if you are using Posix functions like sigaction, then remember to mark your callback (if you use one) with extern(C) (and in recent versions of D, @nogc nothrow too), and then the rest of the code should compile as D the same way as in C.

Adam D. Ruppe
  • 25,382
  • 4
  • 41
  • 60
  • what harm may I have if I omit `@nogc nothrow`? – porton Jan 24 '19 at 08:18
  • It won't compile. But if you define the C function yourself without them, you can make it compile, but still, you aren't supposed to do much of anything from a signal handler, so either of those operations brings you to undefined behavior anyway (likely going to crash you, eventually) so might as well just play by the rules. – Adam D. Ruppe Jan 24 '19 at 14:35
  • I do realize that I cannot throw exceptions in a signal handler. My question was not what happens if I throw an exception, but what happens if I do not specify `nothrow` (or `@nogc`) modifier – porton Jan 24 '19 at 16:32
  • And I answered that: "it won't compile, but if can define the C function yourself without them,you can make it compile." – Adam D. Ruppe Jan 24 '19 at 20:54
  • Sorry, I don't understand. You say something about something that either will or will not compile. It is all I understand – porton Jan 24 '19 at 21:01
  • Do you mean that it compiles with old but not with recent versions of D? – porton Jan 24 '19 at 21:21