[launchd-dev] fork & exit in Shell Script (Revisited)

Quinn eskimo1 at apple.com
Thu Nov 13 10:00:44 PST 2008


At 8:28 -0500 11/11/08, Charles Darwin wrote:
>"In Mac OS X v10.4, launchd was added. This is the preferred means 
>of adding background agents on a per-user basis. "
>
>that I found here:
>
><http://developer.apple.com/documentation/MacOSX/Conceptual/BPSystemStartup/Articles/CustomLogin.html#//apple_ref/doc/uid/20002134>

That's probably true, but there are certain advantages to using a 
login item, namely that a login item doesn't have to be code: it can 
be anything that the Finder can open.  You can solve this probably 
with no code by simply creating an alias to the server volume in 
question and adding that alias to the login item list.

And it turns out that mounting AFP volumes from a shell script is 
tricky.  If you want the volume to act like it's been mounted via 
standard means, you can't just use mount_afp -- you have to make sure 
that Disk Arbitration knows about the volume, and that means mounting 
it using higher level software.  Mounting a server volume 
programmatically is best done using FSMountServerVolumeSync/Async.

                    *                   *                   *

Still, if you want a launchd agent that runs when the user logs in, 
does its job, then quits and isn't relaunched for that session, it's 
pretty easy to construct one.

$ ls -l MyScript.sh
-rwxr-xr-x  1 quinn  staff  63 Nov 13 17:44 MyScript.sh
$ cat MyScript.sh
#! /bin/sh

echo "MyScript start"
sleep 10
echo "MyScript end"
$ cat Library/LaunchAgents/com.apple.dts.MyScript.plist
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" 
"http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Label</key>
	<string>com.apple.MyScript</string>
         <key>LimitLoadToSessionType</key>
         <string>Aqua</string>
         <key>RunAtLoad</key>
         <true/>
	<key>ProgramArguments</key>
	<array>
		<string>/Users/quinn/MyScript.sh</string>
	</array>
</dict>
</plist>

The "LimitLoadToSessionType" of "Aqua" ensures that the job is only 
loaded into GUI sessions.  The "RunAtLoad" of true means that the job 
is run once when it's loaded (that is, when the GUI session is 
started).  And the absence of "KeepAlive" or "OnDemand" means that 
the job is not automatically relaunched when it exits.

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