Linux 的守护程序和服务

守护程序是:systemd
管理命令是:systemctl

守护进程确保程序定期执行或持续运行。systemd 基础知识可参考阮一峰的文章:

  1. 以定时任务为例入门
  2. commands

以运行 Python 脚本程序为例:

文件名假设:hello.service
位置路径:/etc/systemd/system
文件内容:

[Unit]
Description = <Your service description here>
# Assuming you want to start after network interfaces are made available
After = network.target
 
[Service]
Type = simple
ExecStart = python <Path of the script you want to run>
# User to run the script as
User =
# Group = # Group to run the script as
# Restart when there are errors
Restart = always
SyslogIdentifier = <Name of logs for the service>
RestartSec = 2
TimeoutStartSec = infinity
 
[Install]
# Make it accessible to other users
WantedBy = multi-user.target

ExecStart 参数说明:
如果只执行单个命令,可写成:python /absolute/path/of/script.py
但通常一个 Python 应用会有自己的虚拟环境,而且程序中还可能使用了相对路径。就需要执行命令是,进入应用项目路径,且启用虚拟环境。
可以这么写:/bin/bash -c "cd /your/project/dir/ && env/bin/python3 app.py"

更多配置参数,参考Linux systemd unit 配置文件

启用配置文件
sudo systemctl enable hello.service
sudo systemctl daemon-reload

启动服务
sudo systemctl start hello.service

查看服务的状态
sudo systemctl status hello.service

查看服务的日志
sudo journalctl -u hello.service -n 20

  • -u 指定 unit
  • -n 指定显示最近的日志行数
  • -f 实时滚动显示

停止服务
sudo systemctl stop hello.service
撤销符号链接关系(相当于撤销开机启动)
sudo systemctl disable hello.service

如果修改了配置文件,需要重载配置并重启服务
sudo systemctl daemon-reload
sudo systemctl start hello.service


参考: