2023-12-14    2023-12-14    705 字  2 分钟

launchd is an init and operating system service management daemon created by Apple Inc. as part of macOS to replace its BSD-style init and SystemStarter. There have been efforts to port launchd to FreeBSD and derived systems.

launchd 是 macos 上一套服务管理框架,类似与 linux 的 systemnd

launchtl 配置文件

plist 文件就是 xml 文件,内容格式如下

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
<?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.exampl.hello</string>
        <key>ProgramArguments</key>
        <array>
            <string><绝对路径>/launchctl-in-mac/bin/hello.sh</string>
        </array>
        <key>StartInterval</key>
        <integer>10</integer>
        <key>RunAtLoad</key>
        <true/>
    </dict>
</plist>

常用的 key

key类型含意是否必须
Labelstringlaunchctl list 时显示名称Y
ProgramArgumentsarray执行内容一般为绝对路径Y
StartIntervalinteger定时执行,单位秒N
RunAtLoadboolean导入时运行Y
disabledboolean是否不生效, -w 可以强制忽视N
EnvironmentVariablesdict环境变量N
GroupNamestring用户组N
UserNamestring使用用户名 在 DaemonsN
KeepAliveboolean是否设置程序一直存活,退出后自动重启N
ProcessTypestring进程类型N
StandardErrorPathstring执行错误输出日志N
StandardOutPathstring执行程序的日志N
StartCalendarIntervaldict设置程序具体运行时间,类似 cron 表达式N

launchtl 文件存放位置

目录作用
/Library/LaunchDaemons系统启动后执行,由管理员定义的守护进程任务项
/Libray/LaunchAgents当用户登录才会执行。由管理员为用户自定义的任务项
~/Library/LaunchDaemons由用户自定义的任务项
/System/Library/LaunchAgentsMacOS 用户定义的任务
/System/Library/LaunchDaemonsMacOS 用户定义的收获进程任务项

launchtl 常用命令

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
# 加载任务
launchctl load /path/to/aa.plist
# 删除任务
launchctl unload /path/to/aa.plist
# 查看任务列表,使用 grep '任务 label' 可以过滤
launchctl list | grep '任务 label'

# 开始任务
launchctl start ai.rw
# 结束任务
launchctl stop ai.rw

常用问题

78 error

Error 78 means that there is no permission to write to the log files you have specified. 错误 78 意味着没有权限写入您指定的日志文件。

配置环境变量

这种方法常用于设置系统环境变量

1
2
3
4
5
6
# 设置 Var 的环境变量为 value
launchctl setenv Var value
# 获取 Var 的值
launchctl getenv Var
# 移除环境变量 var 的值
launchctl unsetenv Var

参考

  1. 开机自启动配置 linux&mac
  2. 使用 launchd/launchctl 管理 MacOS 服务 | 猎人杂货铺
  3. macOS 下 Launchd 的介绍和使用 | 六脉神间
  4. Mac 定时任务 launchctl 常用 key
  5. fbi8101084–launchctl-in-mac
  6. macOS launchd 不完全指南 - 掘金
  7. macos 设置开机启动任务 | xianyu123’s Blog