linux - systemd:相同的多个单元

标签 linux systemd

我尝试使用 systemd 启动多个进程 - 如果它终止,则重新启动。唯一的区别是进程的参数。

有没有办法避免每个进程一个单元文件? 我正在寻找所有进程的单元文件。

通常我会使用启动脚本,但是——正如我所说的——在终止的情况下重新启动也应该包括在内。而且我看不出有什么方法可以使用纯 systemd 而不是手工制作的 skriptlet。

谢谢!

最佳答案

也许使用模板单元符合您的需要。来自 systemd.unit(5)

Optionally, units may be instantiated from a template file at runtime. This allows creation of multiple units from a single configuration file. If systemd looks for a unit configuration file, it will first search for the literal unit name in the file system. If that yields no success and the unit name contains an "@" character, systemd will look for a unit template that shares the same name but with the instance string (i.e. the part between the "@" character and the suffix) removed. Example: if a service getty@tty3.service is requested and no file by that name is found, systemd will look for getty@.service and instantiate a service from that configuration file if it is found.

To refer to the instance string from within the configuration file you may use the special "%i" specifier in many of the configuration options. See below for details.

所以你可以创建一个文件 myservice@.service 来读取类似的内容

[Unit]
Description=MyService component %i
PartOf=myservice.target

[Service]
Type=simple
ExecStart=/usr/local/bin/myservice %i
Restart=on-failure

和主单元myservice.target as

[Unit]
Description=Myservice
Requires=myservice@a.service myservice@b.service myservice@c.service

myservice@.service 中的 PartOf= 规范确保当目标停止或重新启动时每个组件也是如此。在 myservice.target 中使用 Requires= 必须启动每个组件才能使 myservice 成功启动。我认为应该是这样的情况,如果任何单个组件失败,任何没有失败的组件都应该被终止;即全有或全无。如果这不是您想要的,您可以使用 Want= 而不是 Requires=。

这有点尴尬,但如果您需要提供多个参数,您可以通过环境变量引入一个间接寻址。对于模板单元,添加 Environment=args=%i 并将 ExecStart 中的 %i 替换为 $args。我认为最好找到替代方案,但在不了解您的用例的情况下,我不确定该解决方案是什么。

关于linux - systemd:相同的多个单元,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39728678/

相关文章:

linux - 递归地输出目录中某种类型的所有文件的文件大小?

linux - 如何在linux中创建没有父目录路径的软链接(soft link)?

c - 如何使用 sdbus 发送 Unix 文件描述符?

python-3.4 - 如何通过 Systemd DBus API 提取服务状态?

linux - 挂载命令后如何启动系统服务

linux截断第一行-有没有更好的方法

regex - 使用 RegEx 匹配字符,除非 "immediately"后跟另一个特定字符

c - 为什么我的程序在 waitpid() 中停止而没有任何错误信息?

raspberry-pi - 无法禁用 systemd serial-getty 服务

linux - 如何在宕机时使用 Systemd 重启服务?