launchctl的简单使用

在 Linux 上有一个大家用惯的 systemd,在 MacOS 上有一个与之相对应的工具,launchd。

Linux 下,systemd 的 pid 是 1,系统启动后,它是第一个被拉起来的,其它进程都是它的子进程。

在MacOS 下面也有一个这样的超级进程,所有的其它进程都是它产生的,挂为它的子进程、孙子进程…… 它就是 launchd。launchd 对应的管理工具就是 launchctl。

plist配置模板

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<?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>tech.mapan.macos.alist</string>
<key>KeepAlive</key>
<true/>
<key>ProcessType</key>
<string>Background</string>
<key>RunAtLoad</key>
<true/>
<key>WorkingDirectory</key>
<string>path/to/alist/working</string>
<key>ProgramArguments</key>
<array>
<string>path/to/alist</string>
<string>server</string>
</array>
</dict>
</plist>

其中Label应该与plsit的文件名一致,例如本例子的文件名应该是~/Library/LaunchAgents/tech.mapan.macos.alist.plist

  • RunAtLoad 代表开机自启动

  • WorkingDirectory 代表工作目录

  • ProgramArguments 代表运行命令

    本例中的命令等价于在/Users/mapan/alist目录下 执行 /Users/mapan/bin/alist server命令。

配置好plist文件后重启电脑后即可生效。

如果遇到问题可以使用LaunchControl这个可视化工具进行排查。

安装方式:brew install --cask launchcontrol

ps: 这个工具是收费软件,但可以试用,试用版对于调试看报错信息足够了。