Let me attempt to explain. First, look at the implementation of onSignal:

[https://github.com/nim-lang/Nim/blob/version-1-0/lib/posix/posix.nim#L1038](https://github.com/nim-lang/Nim/blob/version-1-0/lib/posix/posix.nim#L1038)

it is a very thin wrapper over the POSIX signal handler callback function.

[http://man7.org/linux/man-pages/man2/signal.2.html](http://man7.org/linux/man-pages/man2/signal.2.html)

This **is nothing like how Python does it**!

[https://docs.python.org/3.4/library/signal.html#execution-of-python-signal-handlers](https://docs.python.org/3.4/library/signal.html#execution-of-python-signal-handlers)

> A Python signal handler does not get executed inside the low-level (C) signal 
> handler. Instead, the low-level signal handler sets a flag which tells the 
> virtual machine to execute the corresponding Python signal handler at a later 
> point(for example at the next bytecode instruction).

Python has a global _stub_ sighandler function that punts back to the python VM 
and dispatches the right thing. This is why you can do things like use Closures 
/ access outside variables from Python.

You have to think more like a C programmer when dealing with low level POSIX 
stuff in Nim. This means no closures, unfortunately.

If you need to access external variables, you must use a global variable, as 
@enthus1ast shows in their example.

You have to consider that the POSIX only allows a _single_ global signal 
handler for a process.

You could emulate something like what Python does by creating a global 
_dispatcher_ sighandler proc that internally loops through and destroys all 
active app objects.

I personally consider this bad practice though. In general, I never want my 
library code to take over my application signal handler. It's my job as the 
application developer to handle signals. If I want to set up my own signal 
handler, how do I even know that you have already set one? I could easily end 
up just overwriting your signal handler with my application specific one. 
Especially when dealing with low level / C code, you rarely see library code do 
signal handling for this reason.

Reply via email to