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

如何按特定顺序停止 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

程序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

程序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

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

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

答案1

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

以下是官方文档对此,我不得不说:

...当两个相互之间存在顺序依赖关系的单元关闭时,将应用启动顺序的逆转。例如,如果一个单元在另一个单元上配置了 After=,则如果两者都关闭,则前者将在后者之前停止......

相关内容