创建一个 mac 的后台进程(daemon)

时间:2021-12-05 04:10:33

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