I wanted to make a safe exit for my console application that will be running on linux using mono but I can't find a solution to detect wether a signal was sent to it or the user pressed ctrl+c.
On windows there is the kernel function SetConsoleCtrlHandler which does the job but that doesnt work on mono.
How do I get a closing event on my console application to safe exit it ?
You need to use
Mono.UnixSignal
, there's a good sample posted by Jonathan Pryor : http://www.jprl.com/Blog/archive/development/mono/2008/Feb-08.htmlThere's also a shorter example on Mono page: FAQ / Technical / Operating System Questions / Signal Handling:
As an example of providing a unix and windows implementation see below. Note that you can still include the Mono.Posix dll when using Visual Studio.
I have added the SIGTERM signal as well because this is fired by systemd in unix when stopping / restarting your app as a service.
Interface to expose an exit event
Unix implementation
Windows implementation