macOS launchd 开机自启服务
macOS 用 launchd 管理开机自启的常驻服务。用户级放 ~/Library/LaunchAgents/,系统级放 /Library/LaunchDaemons/。
基本 plist 范式
~/Library/LaunchAgents/<服务名>.plist:
<?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>nginx</string>
<key>ProgramArguments</key>
<array>
<string>/opt/homebrew/bin/nginx</string>
</array>
<key>KeepAlive</key> <!-- 退出后自动拉起 -->
<true/>
<key>RunAtLoad</key> <!-- 开机/加载时启动 -->
<true/>
</dict>
</plist>
加载 / 卸载
launchctl load -w ~/Library/LaunchAgents/<服务名>.plist
launchctl unload ~/Library/LaunchAgents/<服务名>.plist
launchctl start <Label>
launchctl stop <Label>
带启动命令与环境变量(如设置环境变量后再启动)
<key>ProgramArguments</key>
<array>
<string>sh</string>
<string>-c</string>
<string>
launchctl setenv OLLAMA_HOST "0.0.0.0"
launchctl setenv OLLAMA_ORIGINS "*"
</string>
</array>
<key>RunAtLoad</key>
<true/>
带自定义 PATH / 环境变量
需要特定 PATH(如 conda、homebrew、node)时,在 plist 里加 EnvironmentVariables:
<key>EnvironmentVariables</key>
<dict>
<key>PATH</key>
<string>/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin</string>
</dict>
PM2 用
pm2 startup launchd会自动生成这样的 plist(写入~/Library/LaunchAgents/pm2.<user>.plist,执行pm2 resurrect恢复进程列表),再用pm2 save冻结进程列表。
原文链接:https://www.ssssmy.com/notes/macos-launchd-kai-ji-zi-qi-fu-wu