Linux下实现关机前执行自定义服务的问题与解决
实现关机前自动运行的systemd服务及问题排查
操作步骤
- 创建自定义target文件
/etc/systemd/system/custom.target,内容如下:
[Unit] Description=Custom Target Requires=multi-user.target After=multi-user.target AllowIsolate=yes
- 在
/etc/systemd/system/custom.target.wants/目录下创建app-shutdown.service单元文件,内容如下:
[Unit] Description=App Shutdown After=multi-user.target [Service] Type=oneshot ExecStart=echo 'started' ExecStop=bash /myhome/app-shutdown.sh RemainAfterExit=yes TimeoutStopSec=480 [Install] WantedBy=custom.target
遇到的问题
- 执行
systemctl list-units --type target --all时,无法找到custom.target - 执行
systemctl isolate custom.target和ln -sf /etc/systemd/system/custom.target /etc/systemd/system/default.target后,custom.target已加载激活,但系统重启后,执行systemctl status app-shutdown显示服务处于inactive (dead)状态
排查与解决
- 经排查发现之前的
ln命令未成功执行,重新执行该命令 - 依次执行以下命令:
sudo systemctl daemon-reload sudo systemctl enable app-shutdown sudo systemctl start app-shutdown - 再次重启系统后,服务恢复正常运行
内容的提问来源于stack exchange,提问作者fr0zt
相关产品推荐
相关产品推荐

