Linux使用systemd将可执行文件配置为开机自启的守护进程
基于systemd的方案(daemon:守护进程)
首先,确认所有可执行文件,配置文件和目录权限合适
sudo chmod +x /path/to/exe # 可执行权限
sudo chmod 644 /path/to/config.cfg
sudo chmod -R 755 /path/to
ls -l # 查看权限
首先创建systemd service 文件,使用文本编辑器创建一个新的service文件,
sudo nano /etc/systemd/system/进程名称_一般建议为可执行文件名.service
然后编辑
[Unit]
Description=进程名称或者你希望叫什么名字 Service
After=network.target # 在网络启动后启动,依赖互联网的一定这么设置
[Service]
ExecStart=/path/to/你的进程可执行文件 -c /path/to/config.cfg 假如有其他参数的话
WorkingDirectory=/path/to # 执行文件时的位置,如果依赖相对路径那么一定设置
# 日志和错误输出,如果没有这个参数的话会默认存储到systemd的默认日志位置
StandardOutput=file:/path/to/runlog.log
StandardError=file:/path/to/errorlog.log
Restart=always
User=使用什么用户执行?
Group=用户组
[Install]
WantedBy=multi-user.target
如果不确定用户和用户组,可以查询:
id username
然后注册
sudo systemctl enable 你的守护进程.service
sudo systemctl daemon-reload
然后启动
sudo systemctl start 你的进程.service
检查是否成功
sudo systemctl status 你的进程.service
如果出问题了,除了去指定运行日志看看,还可以看看systemd的日志
sudo journalctl -u 你的进程.service
2023年12月31日
