如何确保在特定系统服务停止时执行特定的订单? 我有几个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之前停止。 希望这不是太混乱。
我能想到的唯一解决scheme是让每个服务都有一个ExecStop行,它执行systemctl stop [service]命令,以便在停止之前必须停止的特定服务。 我遇到的问题是,我实际上目前有六个使用挂载分区的服务,必须在尝试卸载之前停止。 在这六个中,有些需要按特定的顺序停止。 由于这是用于商业产品,我希望有一个更清洁的解决scheme。
您可以通过在单元文件中指定Before=和After=来控制closures顺序来描述启动顺序。 closures时应用相反的顺序。
以下是官方文档对此的评论:
…当它们之间的顺序依赖关系被closures的两个单元时,启动顺序的逆向应用。 也就是说,如果一台设备在另一个设备上configuration了After =,则前者如果两者都closures,则在后者之前停止。