MacOS的launchd使用

MacOS的launchd可以完成开机启动任务、文件监控、守护进程的有用的工作。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Disabled</key>
	<false/>
	<key>Label</key>
	<string>com.zhoumingzhi.watcher</string>
	<key>ProgramArguments</key>
	<array>
		<string>/command/to/be/executed</string>
	</array>
	<key>WatchPaths</key>
	<array>
		<string>/path/to/be/watched</string>
	</array>
	<key>RunAtLoad</key>
	<true/>
	<key>WorkingDirectory</key>
	<string>/Users/Michael</string>
</dict>
</plist>

将上面的文件保存成.plist后缀名的文件,然后放在~/Library/LaunchAgents目录中,每次登录后可以监控文件或文件夹的改变,当有变化时执行ProgramArguments指定的命令。

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>Disabled</key>
	<false/>
	<key>Label</key>
	<string>com.zhoumz.ssh-tunnel</string>
	<key>ProgramArguments</key>
	<array>
		<string>ssh</string>
		<string>-qTnN</string>
		<string>-D</string>
		<string>7070</string>
		<string>you@yourdomain.com</string>
	</array>
	<key>RunAtLoad</key>
	<true/>
	<key>KeepAlive</key>
	<dict>
		<key>NetworkState</key>
		<true/>
	</dict>
</dict>
</plist>

将上面的文件保存成.plist后缀名的文件,然后放在~/Library/LaunchAgents目录中,每次登录后可以自动开启SSH反向代理,而且会在网络畅通时自动重连。

用launchctl load 和 launchctl unload命令可以很方便的加载和卸载.plist文件,而不用重启系统。

关于上面文件的含义,请参考:https://developer.apple.com/library/mac/#documentation/Darwin/Reference/ManPages/man5/launchd.plist.5.html

关于LaunchAgents目录的作用,请参考:https://developer.apple.com/library/mac/#documentation/MacOSX/Conceptual/BPSystemStartup/Chapters/CreatingLaunchdJobs.html#//apple_ref/doc/uid/10000172i-SW7-BCIEDDBJ

发表评论