[Mono-list] How to work with Mono.Unix.Signalhandler

Jonathan Pryor jonpryor@vt.edu
Thu, 28 Apr 2005 15:26:35 -0400


On Wed, 2005-04-27 at 14:49 +0200, Andreas Sliwka wrote:
> Greetings,
>   I recently tried to compile tomboy 0.3.2 and found that my mono
> 1.1.4 installation did not like the calls to Mono.Posix. So I tried to
> replace them with calls to Mono.Unix. 
>   My problem is that I dont find any documentation about
> Mono.Unix.SignalHandler.

Ironically enough, there's a test case for Mono.Unix.SignalHandler:

http://mono.myrealbox.com/source/trunk/mcs/class/Mono.Posix/Test/Mono.Unix/StdlibTest.cs

Please note that you have to be *very* careful within signal handler
context, since most functions aren't re-entrant -- that is, calling e.g.
malloc(3) within a signal handler when a signal occurred and malloc(3)
was being executed is a good way to corrupt the process heap.

Further, the list of re-entrant functions is *very* limited; not even
P/Invoke is guaranteed to be safe (which is where my test case is
incorrect -- I'll have to fix that).

In short, the only safe thing to do within a SignalHandler is modify a
global variable which is later polled by the main program.

> The code I want to to translate is the following:
> 
> using Mono.Posix;
> class SomeClass { 
>   // ...
>   static Syscall.sighandler_t sig_handler;
>   static void RegisterSignalHandlers () {
>     sig_handler = OnExitSignal;
>     Syscall.signal ((int) Signals.SIGTERM, sig_handler);
>     Syscall.signal ((int) Signals.SIGQUIT, sig_handler);
>   }
>   static void OnExitSignal (int signal) {
>     // do this and that ...
>   }
> }
> 
> how would I write this with Mono.Unix?

The Mono.Unix equivalent would be:

	using Mono.Unix;
	class SomeClass {
		static void RegisterHandlers ()
		{
			// Make sure OnSignal() is JITed
			OnSignal (0);

			// Add handlers
			Stdlib.signal (Signum.SIGTERM, 
				new SignalHandler (OnSignal));

			Stdlib.signal (Signum.SIGQUIT,
				new SignalHandler (OnSignal));
		}

		static void OnSignal (int signal)
		{
			//  ...
		}
	}

 - Jon