Mac中建立守護進程(Daemon)
建立一個能夠執行的腳本 hello.sh
touch /Users/oslivan/test/hello.sh
chmod 755 /Users/oslivan/test/hello.sh
## hello.sh start
for((;;))
do
echo "hello."
sleep 3
done
## hello.sh end
建立一個 plist, 並經過 launchctl 加載
touch /Users/oslivan/Library/LaunchAgents/com.oslivan.test.hello.plist
## com.oslivan.test.hello.plist start
<?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>Label</key>
<string>com.oslivan.test.hello</string>
<key>ProgramArguments</key>
<array>
<string>/Users/oslivan/test/hello.sh</string>
</array>
<key>StandardOutPath</key>
<string>/Users/oslivan/test/logfile.log</string>
<key>StandardErrorPath</key>
<string>/Users/oslivan/test/logfile_error.log</string>
<key>RunAtLoad</key>
<true/>
<key>KeepAlive</key>
<true/>
</dict>
</plist>
## com.oslivan.test.hello.plist end
launchctl load /Users/oslivan/Library/LaunchAgents/com.oslivan.test.hello.plist
測試是否啓動成功
ps -ef | grep hello
cd /Users/oslivan/test/ && tail logfile.log
參考
Sample Guide
launchd.plist 語法
launchd 教程html