Re: Cocoa & signal handlers
Re: Cocoa & signal handlers
- Subject: Re: Cocoa & signal handlers
- From: Greg Parker <email@hidden>
- Date: Tue, 4 Dec 2001 17:47:59 -0800
> I'm writing a small daemon to perform a periodic task, and was
planning
> to use NSTimer for that. However, I want my server to respond to
> "standard" Unix server signals, i.e. re-read configuration on SIGHUP
> and terminate and remove its pid-file on SIGTERM.
>
> My understanding from searching is that it is not safe to call any
> Cocoa API from a signal handler, so I was hoping somebody
could recommend
> some kind of mechanism to generate a safe event in the signal handler
> that I can pick up in the run loop and Do The Right Thing?
In general, it's not safe to do *anything* inside a signal handler
except change a global variable. Almost anything else you can think
of could cause a crash or a deadlock. (If you ever did Classic Mac OS
programming, a signal handler is kind of like interrupt time). In Cocoa
itself, a signal handler must not send any Objective-C messages, which
rules out almost all Cocoa APIs.
You could have a global variable like "BOOL gShouldReloadConfiguration".
Set it to TRUE inside the SIGHUP handler, and check it at the beginning
of the periodic task's execution. If the task's period is long, the
check might not be fast enough for SIGTERM to cause a timely exit, but
you might be able to get away with "unlink(pidfile); exit(0);" in the
SIGTERM handler.
(Technical details: sending an Objective-C message may acquire locks
or allocate memory (which also acquires locks). If a message sender
is interrupted by a signal and the signal handler sends a message,
the handler would deadlock when trying to grab the lock already held
by the interrupted message sender.)
--
Greg Parker email@hidden Java & Objective C