创建服务
在树莓派上创建一个 .service 文件。例如:
realtime.service
[Unit]
Description=My service
After=network.target
[Service]
Restart=on-failure
RestartSec=5
ExecStart=/usr/bin/python3 -u /home/pi/RealTime.py
StandardOutput=inherit
StandardError=inherit
User=pi
[Install]
WantedBy=multi-user.target
在上面的范例中,服务会去以 Python 3 来运行 /home/pi/realtime目录下面的 main.py 脚本。用这种方法,你不仅可以配置 Python 脚本,只需要将 ExecStart 这行改为需要启动的任何程序或脚本即可。
将这个文件用 root 用户保存到 /etc/systemd/system 目录:
sudo cp realtime.service /etc/systemd/system/realtime.service
然后就可以用下面的命令尝试启动服务了:
sudo systemctl start realtime.service
停止服务:
sudo systemctl stop realtime.service
添加或修改配置文件后,需要重新加载
systemctl daemon-reload
设置开机时自动运行:
sudo systemctl enable realtime.service
查看服务状态
systemctl status realtime.service
查看进程
ps -ef |grep realtime.service
关闭进程
kill -9 567(进程ID)
实时跟踪服务的日志输出,可以使用 journalctl 命令:
journalctl -u dbconnection.service -f
-f 选项会让 journalctl 实时跟踪日志的最新输出
卸载服务
sudo systemctl stop example.service #停止正在运行的服务
sudo systemctl disable example.service #禁用服务开机自启
sudo systemctl daemon-reload #重新加载 systemd 管理器配置
sudo rm /etc/systemd/system/example.service #删除 service 文件,根据实际文件位置修改
sudo systemctl daemon-reload #再次重新加载 systemd 管理器配置