創建一個 mac 的后台進程(daemon)


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 教程


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM