Playing with low-level networking code in several languages on several platforms, I followed this example from the Apple developer forum to get a Network.framework example working.
It works great but the app never exits back to the commandline due to using dispatch_main()
.
The documentation is very sparse, examples are not common, and tutorials barely exist at all. Hunting around the internet all I find is mentions that this never returns, but I can't find anything about how to break out of it when I actually want to return.
I'm assuming this relies on background knowledge of GCD (grand central dispatch) and runloops and such that I don't have and that isn't easy to find. Perhaps it's only relevant for a commandline app but most Apple code is for GUI?
So is there a way to break out of/return from the loop/thread/etc that dispatch_main
puts me in? Or is there some alternative API or method other than dispatch_main
that you're supposed to use when you intend to return?
For this, you probably want to use the C function
void exit(int status);
See the output ofman 3 exit
. This will run various standard C cleanup processes and cause your process to exit cleanly with the status code you call it with.What's perhaps more interesting is the question: "How does your process know when to call
exit()
?" Is it going to receive a network payload that tells it when to quit? Will you send it a UNIXSIGTERM
signal? (If this feels like a misuse ofSIGTERM
to you, you could consider usingSIGUSR1
orSIGUSR2
.) GCD has signal handling capabilities built in (seeDispatchSource.makeSignalSource
here). To be more explicit, you could add a GCD signal handler forSIGTERM
do whatever other cleanup you need to do, and then callexit()
at the end of the handler block, and that should do the trick.Hope that helps!