小编For*_*ACE的帖子

如何按特定顺序停止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]命令,该服务必须在停止之前停止。我遇到的问题是我实际上目前有六个服务使用已安装的分区,并且必须在尝试卸载之前停止。在这六个中,有些需要按特定顺序停止。由于这是用于商业产品,我希望有一个更清洁的解决方案。

linux systemd

7
推荐指数
1
解决办法
2万
查看次数

标签 统计

linux ×1

systemd ×1