Re: Cocoa & signal handlers
Re: Cocoa & signal handlers
- Subject: Re: Cocoa & signal handlers
- From: Ingvar Nedrebo <email@hidden>
- Date: Wed, 5 Dec 2001 18:02:38 +0000
Greg,
Thanks! I had come to suspect as much, so what I'll do is to
use a global variable, set my NSTimer to 2 secs and just count
up to my period of ~15 minutes. The CPU overhead should still
be neglible.
But out of curiosity and because of an upcoming project where
this could be more of an issue: One of my thoughts was to open
an NSPipe and use -readInBackgroundAndNotify; then in the
signal handler do a non-blocking raw write(2) directly on
the pipe. Would that have a chance of working?
Regards,
I.
On Wednesday, December 5, 2001, at 01:47 , Greg Parker wrote:
> 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