[launchd-dev] can i do this with launchd? (on-demand auto-restart daemons)

Quinn eskimo1 at apple.com
Fri Aug 29 03:28:39 PDT 2008


At 1:12 -0700 28/8/08, Ian wrote:
>can i do this with launchd?

Yes.  This is exactly the sort of thing that launchd excels at.

>1. it should start when the cocoa GUI is started (either manually or 
>via a startup item)

The best way to handle this is to have the daemon launch when a 
client connects to its TCP socket.  You do this by setting up the 
"Sockets" dictionary in your launchd property list file.  launchd 
will open and listen to the socket on your behalf.  When a connection 
comes in, launchd will run your daemon and pass the listening socket 
to it.  When your daemon quits, launchd will resume listening on the 
socket.

The SampleD sample code shows this basic process.

<http://developer.apple.com/samplecode/SampleD/index.html>

>2. if the daemon dies for whatever reason, launchd should restart it

Typically you only want launchd to restart the daemon if someone has 
connected to the TCP socket.  That's the default behaviour.  However, 
you can arrange for other behaviour by way of the "KeepAlive" 
property.  See <x-man-page://5/launchd.plist> for details.

>3. if the GUI is closed, the daemon should be shut off without 
>having it restart.

When the GUI quits the TCP connection to the daemon will close.  When 
the daemon has no open connections, it should quit (after some 
debounce period).

The only real wrinkle in this is Python.  When writing a launchd 
daemon you have to "check in" with launchd to get access to your 
listening socket.  That requires use of the <launch.h> API.  AFAIK 
there's no direct Python binding to that.  It's a simple C API, so if 
you're familiar with glue Python to C it shouldn't present a serious 
obstacle.  Otherwise, you might investigate wrapping your Python code 
within PyObjC so you can do the launchd check in from C and then do 
all the real work from Python.

S+E
-- 
Quinn "The Eskimo!"                    <http://www.apple.com/developer/>
Apple Developer Relations, Developer Technical Support, Core OS/Hardware


More information about the launchd-dev mailing list