微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

当特定的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…

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐