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

For*_*ACE 7 linux systemd

当特定的 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
Run Code Online (Sandbox Code Playgroud)

程序A.服务

[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
Run Code Online (Sandbox Code Playgroud)

程序B.服务

[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
Run Code Online (Sandbox Code Playgroud)

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

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

Mar*_*erg 9

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

以下是官方文档对此的说法:

...当两个具有顺序相关性的单元关闭时,将应用启动顺序的倒数。即如果一个单元在另一个单元上配置了 After= ,如果两者都关闭,则前者在后者之前停止......

  • 感谢您的回复。我也遇到过该文档,但我不喜欢服务启动和停止时依赖项必须相同的事实。我希望能够找到一种解决方案,其中开始时有一组要求,但停止时有一组不同的要求。这可能是徒劳的,但我认为问一下也没什么坏处。 (2认同)