需求
本人写了一个关于树莓派的温控风扇脚本,但是每次开机手动去运行较为麻烦,所以打算将其设置成开机自启。
开机自启脚本 fan_ctrl.py
路径 /home/pi/program/fan_ctrl.py
创建 service 配置文件
- 进入
/usr/lib/systemd/system
目录 - 创建
my_program.service
编辑如下(按需修改)
[Unit]
# 当前服务的简单描述
Description=/home/pi/program fan_ctrl.py
# 当前Unit运行必须满足的条件,否则不会运行,此处条件为fan_ctrl.py文件存在
ConditionPathExits=/home/pi/program/fan_ctrl.py
[Service]
Type=simple # 执行ExecStart指定的命令,启动主进程
# 当前服务启动时执行的命令
ExecStart=sudo python3 /home/pi/program/fan_ctrl.py
# 当前服务启动后执行的命令
ExecStartPost=echo "当前登录用户密码"
# 表示进程退出后,服务仍然保持执行
RemainAfterExit=yes
# 定义如何结束当前服务,当前控制组里面的所有子进程都被杀掉
KillMode=control-group
[Install]
# 当Unit激活时(enable),符号链接存放的目录
WantedBy=multi-user.target
设置开机启动
在终端输入
$ sudo systemctl enable my_program.service
输出以下内容
Created symlink /etc/systemd/system/multi-user.target.wants/my_program.service → /lib/systemd/system/my_program.service.
表示在执行$ sudo systemctl enable my_program.service
命令以后,在/lib/systemd/system/
目录新建了一个名为 my_program.service
的配置文件文件,并建立了一个链接文件 /etc/systemd/system/multi-user.target.wants/my_program.service
链接到 /lib/systemd/system/my_program.service
文件
当系统启动时,会去寻找
/etc/systemd/system/multi-user.target.wants/
目录下面的 XXX.service 配置文件去启动相应的进程
查看 service 状态
执行命令
$ sudo systemctl status my_program.service
输出
my_program.service - /home/pi/program fan_ctrl.py
Loaded: loaded (/lib/systemd/system/my_program.service; enabled; vendor preset: enabled)
Active: inactive (dead)
启动 service
执行命令
$ sudo systemctl start my_program.service
输出
my_program.service - /home/pi/program fan_ctrl.py
Loaded: loaded (/lib/systemd/system/my_program.service; enabled; vendor preset: enabled)
Active: active (running) since Mon 2021-11-29 15:33:18 CST; 3s ago
Process: 4157 ExecStartPost=/bin/echo 123456 (code=exited, status=0/SUCCESS)
Main PID: 4156 (sudo)
Tasks: 2 (limit: 4599)
Memory: 3.5M
CGroup: /system.slice/my_program.service
├─4156 /usr/bin/sudo python3 /home/pi/program/fan_ctrl.py
└─4158 python3 /home/pi/program/fan_ctrl.py
11月 29 15:33:18 pi-virtual-machine systemd[1]: Starting /home/pi/program fan_ctrl.py...
11月 29 15:33:18 pi-virtual-machine echo[4157]: 123456
11月 29 15:33:18 pi-virtual-machine systemd[1]: Started /home/pi/program fan_ctrl.py.
11月 29 15:33:18 pi-virtual-machine sudo[4156]: root : TTY=unknown ; PWD=/ ; USER=root ; COMMAND=/usr/bin/python3 >
11月 29 15:33:18 pi-virtual-machine sudo[4156]: pam_unix(sudo:session): session opened for user root by (uid=0)
Loaded
:配置文件的位置,是否设为开机启动Active
:running
表示正在运行Main PID
:主进程IDStatus
:由应用本身提供的软件当前状态CGroup
:应用的所有子进程日志块
:应用的日志
停止 service
执行
$ sudo systemctl stop myprogram.service
撤销开机启动
执行以下命令
$ sudo systemctl disable my_program.service
即撤销之前建立的软链接
修改xxx.service文件后重启
# 重新加载配置文件
$ sudo systemctl daemon-reload
# 重启相关服务
$ sudo systemctl restart my_program.service