MacOS上使用launchctl对Service进程守护

2020/9/27 posted in  Linux_UNIX

plist example:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>Label</key>
    <string>com.jake.service.frpc</string>
     <key>ServiceDescription</key>
    <string>frpc service</string>
    <key>RunAtLoad</key>
    <true/>
    <key>ProgramArguments</key>
    <array>
      <string>/Users/jakehu/Service/frp_0.33.0_darwin_amd64/frpc</string>
      <string>-c /Users/jakehu/Service/frp_0.33.0_darwin_amd64/frpc.ini</string>
    </array>
    <!-- 标准输入文件 -->
    <key>StandardInPath</key>
    <string>/Users/jakehu/Service/frp_0.33.0_darwin_amd64/frpc/log/run-in-frpc.log</string>
    <!-- 标准输出文件 -->
    <key>StandardOutPath</key>
    <string>/Users/jakehu/Service/frp_0.33.0_darwin_amd64/frpc/log/run-out-frpc.log</string>
    <!-- 标准错误输出文件 -->
    <key>StandardErrorPath</key>
    <string>/Users/jakehu/Service/frp_0.33.0_darwin_amd64/frpc/log/run-err-frpc.log</string>
</dict>
</plist>

执行命令

Getting information about available (loaded) jobs :
$ launchctl list

Getting information about a given job :
$ launchctl list | grep <LABEL>

Loading a job (a global daemon) :
$ launchctl load /Library/LaunchDaemons/<LABEL>.plist

Unloading a job (a global daemon) :
$ launchctl unload /Library/LaunchDaemons/<LABEL>.plist

Starting a job (a loaded job) :
$ launchctl start <LABEL>

Stoping a job (a loaded job) :
$ launchctl stop <LABEL>

Restarting a job (a loaded job) :
$ launchctl restart <LABEL>

意外错误

加载命令的时候出现了错误:

➜  log sudo launchctl load /Library/LaunchDaemons/com.jake.service.frpc.plist
/Library/LaunchDaemons/com.jake.service.frpc.plist: Path had bad ownership/permissions

解决方案:

Try changing the ownership of the .plist file, as noted here.

    sudo chown root /Library/LaunchDaemons/myfile.plist
    sudo chgrp wheel /Library/LaunchDaemons/myfile.plist

or more simply, change the user and group in one command:

    sudo chown root:wheel /Library/LaunchDaemons/myfile.plist

It is also worth noting that these root LaunchDaemons can't be world writable, for security reasons:

    sudo chmod o-w /Library/LaunchDaemons/*

具体调试可以通过

    tail -f /var/log/system.log

看服务有没有启动成功

Refrerence

https://medium.com/swlh/how-to-use-launchd-to-run-services-in-macos-b972ed1e352

https://stackoverflow.com/questions/28063598/error-while-executing-plist-file-path-had-bad-ownership-permissions