TestSignalsThis program sets up signal handlers for most of the commonly sent signals. It is intended as a test platform for use in understanding UNIX signals.
You can send it signals by using the 'kill' command from a Terminal window (Signals: HUP = 1, INT = 2, QUIT = 3, ABRT = 6, KILL = 9, TERM = 15, STOP = 17, USR1 = 30, USR2 = 31) or by using the pull-down menu to send itself signals. You can also try doing "Force-Quit" on this application to see what signals are sent by that operation.
Because of the restrictions on what you can safely do in a signal handler, this program just sets a global variable which is later read by a method that is called periodically via an NSTimer.
Note on signal handlers from Greg Parker (of Apple):
(posted to the Cocoa-Dev mailing list in November 2004)
"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:
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."
- 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()
download the TestSignals project files
(Requires the Apple Developer Tools - I used XCode 1.5)
The testsignals Perl script provides similar capabilities in a command-line version that should run on most UNIX platforms.
This project illustrates a few aspects of programming for Mac OS X using the Cocoa API:
- using NSPopupButton to implement a pull-down menu that uses 'tags' to identify which menu item was chosen
- using 'scrollRangeToVisible' to keep the latest information visible in a scrolled NSTextView
- use of 'applicationShouldTerminateAfterLastWindowClosed' to quit the application when the window is closed
- updating a counter via NSTimer