开机自启动配置(linux&mac)

1,692 阅读2分钟

linux


配置文件

# cat /etc/systemd/system/frpc.service

[Unit]
Description=frpc daemon
After=syslog.target  network.target
Wants=network.target

[Service]
Type=simple
ExecStart=/opt/frp/frp/frpc -c /opt/frp/frp/frpc.ini
Restart=always
RestartSec=1min
ExecStop=/usr/bin/killall frpc

[Install]
WantedBy=multi-user.target

常用命令

systemctl enable frpc #设置开机启动
systemctl start frpc #启动
systemctl stop frpc #停止
systemctl status frpc #状态
systemctl daemon-reload #修改配置后,重新加载

Mac


配置文件

#cat /System/Library/LaunchDaemons/frpc.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>com.ralphwoo.frpc.plist</string>
	<key>ProgramArguments</key>
	<array>
		<string>/Users/ralphwoo/soft/frp/frp/frpc</string>
		<string>-c</string>
		<string>/Users/ralphwoo/soft/frp/frp/frpc.ini</string>
	</array>
	<key>KeepAlive</key>
	<true/>
	<key>RunAtLoad</key>
	<true/>
	<key>StandardErrorPath</key>
	<string>/tmp/frpc.err</string>
	<key>StandardOutPath</key>
	<string>/tmp/frpc.out</string>
</dict>
</plist>

mac将使用launchctl做为开机启动工具,launchctl将根据plist文件的信息来启动任务。 plist脚本一般存放在以下目录:

/Library/LaunchDaemons -->只要系统启动了,哪怕用户不登陆系统也会被执行
/Library/LaunchAgents -->当用户登陆系统后才会被执行

~/Library/LaunchAgents 由用户自己定义的任务项
/Library/LaunchAgents 由管理员为用户定义的任务项
/Library/LaunchDaemons 由管理员定义的守护进程任务项
/System/Library/LaunchAgents 由Mac OS X为用户定义的任务项
/System/Library/LaunchDaemons 由Mac OS X定义的守护进程任务项

launchctl 常用命令:

# 加载任务, -w选项会将plist文件中无效的key覆盖掉,建议加上
$ launchctl load -w ai.rw.plist

# 删除任务
$ launchctl unload -w ai.rw.plist

# 查看任务列表, 使用 grep '任务部分名字' 过滤
$ launchctl list | grep 'ai.rw'

# 开始任务
$ launchctl start ai.rw.plist

# 结束任务
$ launchctl stop ai.rw.plist

plist支持两种方式配置执行时间:

StartInterval: 指定脚本每间隔多长时间(单位:秒)执行一次;
StartCalendarInterval: 可以指定脚本在多少分钟、小时、天、星期几、月时间上执行,类似如crontab的中的设置,包含下面的 key:
    Minute <integer> # The minute on which this job will be run.
    Hour <integer> # The hour on which this job will be run.
    Day <integer> # The day on which this job will be run.
    Weekday <integer> # The weekday on which this job will be run (0 and 7 are Sunday).
    Month <integer> # The month on which this job will be run.

plist部分参数说明:

Label:对应的需要保证全局唯一性;
Program:要运行的程序;
ProgramArguments:命令语句
StartCalendarInterval:运行的时间,单个时间点使用dict,多个时间点使用 array <dict>
StartInterval:时间间隔,与StartCalendarInterval使用其一,单位为秒
StandardInPath、StandardOutPath、StandardErrorPath:标准的输入输出错误文件,这里建议不要使用 .log 作为后缀,会打不开里面的信息。

参考苹果开发者网址