加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > Linux > 正文

linux – 如何按特定顺序停止systemd服务

发布时间:2020-12-14 03:03:17 所属栏目:Linux 来源:网络整理
导读:当特定的systemd服务停止时,如何确保遵循特定的订单?我有几个运行的系统服务/单元,但在各种已安装的分区上使用资源.使用自定义服务安装和卸载这些分区.在自定义安装程序停止之前,需要以特定顺序停止正在运行的服务(例如ProgramA.service ProgramB.service).
当特定的systemd服务停止时,如何确保遵循特定的订单?我有几个运行的系统服务/单元,但在各种已安装的分区上使用资源.使用自定义服务安装和卸载这些分区.在自定义安装程序停止之前,需要以特定顺序停止正在运行的服务(例如ProgramA.service& ProgramB.service).

设置启动依赖项非常简单,但我无法弄清楚如何确保在挂载服务停止之前服务已停止.

mountCustomPartitions.service

[Unit]
Description=My Custom Partition Mounting Service

[Service]
Type=oneshot
RemainAfterExit=yes
ExecStart=/usr/bin/mountCustomPartitions.sh mount
ExecStop=/usr/bin/mountCustomPartitions.sh unmount

[Install]
WantedBy=multi-user.target

ProgramA.service

[Unit]
Description=My Generic Program A Service
Wants=mountCustomPartitions.service
After=mountCustomPartitions.service

[Service]
Type=simple
ExecStart=/usr/bin/ProgramA

[Install]
WantedBy=multi-user.target

ProgramB.service

[Unit]
Description=My Generic Program B Service
Requires=ProgramA.service
Wants=mountCustomPartitions.service
After=mountCustomPartitions.service ProgramA.service

[Service]
Type=simple
ExecStart=/usr/bin/ProgramB

[Install]
WantedBy=multi-user.target

在上面的场景中,mountCustomPartitions.service必须在程序服务之前启动,但也必须在它们之后停止.如果mountCustomPartitions.service被显式停止,那么它应该导致其他人也停止(但必须等待它们停止).我还需要确保ProgramB在ProgramA之后启动,但也在ProgramA之前停止.希望这不是太混乱.

我能想到的唯一解决方案是让每个服务都有一个ExecStop行,为特定服务执行systemctl stop [service]命令,该服务必须在停止之前停止.我遇到的问题是我实际上目前有六个服务使用已安装的分区,必须在尝试卸载之前停止.在这六个中,有些需要按特定顺序停止.由于这是在商业产品中使用,我希望有一个更清洁的解决方案.

解决方法

您可以通过在单元文件中指定Before =和After =来控制关闭顺序,以描述启动顺序.关闭时应用反向顺序.

以下是official docs对此的评价:

…when two units with an ordering dependency between them are shut down,the inverse of the start-up order is applied. i.e. if a unit is configured with After= on another unit,the former is stopped before the latter if both are shut down…

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读