On Jan 6, 2006, at 8:34 PM, Steve Checkoway wrote:
The USBPrivateDataSample <
http://developer.apple.com/samplecode/USBPrivateDataSample/listing1.html> takes great pains to ensure that the IONotificationPortRef is destroyed in the event of SIGINT. The comment reads, "We clean up so that we don't leak." Is it required to cleanup by calling IONotificationPortDestroy and will not doing so leak notification ports?
Two things: first, the sample is incorrect in that it's doing way too much work from a signal handler. This is a known problem and will be fixed in the next release of the sample. (Only certain functions are safe to call in a signal handler, and those are documented in sigaction(2).)
Second, yes, you do need to destroy notification ports to avoid leaking. The general rule is that APIs with "Create" or "Copy" in the name hand you a new reference to something that you're expected to release when you're done with it. The API in this case is IONotificationPortCreate(), which fits the rule.
To see the leak, comment out the IONotificationPortDestroy call and step through the sample in the debugger while watching the #PRTS column in top(1).
The problem is how to call IONotificationPortDestroy safely from a command line tool that only terminates in response to a signal. One way is to do what is done in the CFLocalServer sample:
Check out the InstallSignalToSocket routine in "Common.c" in that project. It creates a UNIX domain socket and has the signal handler write one end of the socket when it receives a signal. The read side of this socket is wrapped in a CFSocket. This allows you to transfer control from the signal handler to the runloop without doing illegal things in the signal handler.