Re: Best way to catch signals in a Cocoa app
Re: Best way to catch signals in a Cocoa app
- Subject: Re: Best way to catch signals in a Cocoa app
- From: Greg Parker <email@hidden>
- Date: 16 Nov 2004 07:30:01 -0000
Cameron Hayne wrote:
> On 11/14/04 5:48 PM, "John Clayton" <email@hidden> wrote:
>
> > Let's say you need to do some cleanup (like terminating some spawned
> > tasks) no matter how your app is quit. So even if someone kills the
> > process from a terminal, the cleanup still happens. I assume using
> > signal handlers are the only way to get access to these events (because
> > handling uncaught exceptions didn't seem to work), but how does one
> > integrate these into a Cocoa app
>
> I wrote a sample Cocoa application specifically for demonstrating how to
> catch signals in a Cocoa app:
> http://hayne.net/MacDev/TestSignals/
This sample program calls Objective-C methods from inside a signal
handler. Don't do that. If you do, your program may hang or crash
unpredictably.
In general, there's very little you can do safely from inside a signal
handler, because the signal handler interrupts the handling thread at
an unpredictable point. For example, the handling thread could have been
in the middle of malloc() and currently hold the malloc lock. If the
signal handler also calls malloc(), it will hang when it tries to grab
the malloc lock.
In Cocoa, objc_msgSend() may call malloc() or grab other locks from
the Objective-C runtime itself. Usually it doesn't, and your signal
handler survives, but not always.
Among the few signal-safe functions and operations are:
* set a global variable that some other thread looks at
* call _exit(2) or _Exit(3) (but not exit(3)!)
* call write(1)
* call mach_msg_send()
One common solution is to write() to a file descriptor that some
other thread is blocked in read(), and have that other thread do
the real work. Similarly, you can use mach_msg_send() to wake an
NSMachPort or CFMachPort in a runloop.
--
Greg Parker email@hidden Runtime Wrangler
_______________________________________________
Do not post admin requests to the list. They will be ignored.
Cocoa-dev mailing list (email@hidden)
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden