如何配置 systemd 以在重新加载时终止并重新启动守护进程?

Tom*_*ime 12 systemd

我有一个老式的守护进程,我想使用 systemd 来控制它。当它的配置文件发生变化时,需要将其杀死并重新启动。换句话说,在编辑配置文件后,systemctl reload MYSERVICE应该终止进程并重新启动它。

尝试 1:尝试默认设置。这告诉 systemd 如何启动守护进程,而不是如何重新加载它。

[Service]
ExecStart=/usr/bin/MYSERVICE
Type=simple
Run Code Online (Sandbox Code Playgroud)

其结果是,startrestart工作,但reload给出了这样的错误:

# systemctl reload MYSERVICE
Failed to reload MYSERVICE.service: Job type reload is not applicable for unit MYSERVICE.service.
Run Code Online (Sandbox Code Playgroud)

尝试 2:告诉它如何终止进程。这会杀死进程,但 systemd 不会为我重新启动它。

[Service]
ExecStart=/usr/bin/MYSERVICE
Type=simple
ExecReload=/bin/kill -HUP $MAINPID
Run Code Online (Sandbox Code Playgroud)

...其次是...

# systemctl daemon-reload
# systemctl reload MYSERVICE
Run Code Online (Sandbox Code Playgroud)

...杀死进程,但它不会自动重新启动。

尝试 3:也使用 ExecReload 重新启动进程。这失败有几个原因:

ExecReload=/bin/kill -HUP $MAINPID ; /usr/bin/MYSERVICE
Run Code Online (Sandbox Code Playgroud)

...我收到的错误消息...:

# systemctl daemon-reload
# systemctl reload MYSERVICE
Job for MYSERVICE.service failed because the control process exited with error code. See "systemctl status MYSERVICE.service" and "journalctl -xe" for details.
Run Code Online (Sandbox Code Playgroud)

我希望有一个 ReloadType=kill_and_restart 之类的东西,但没有这样的运气。

如何告诉 systemd 在重新加载时杀死并重新启动守护进程?

Tom*_*ime 17

答案是“你没有”!但我们有好消息。

systemd 的理念是 reload 是可选的,如果没有真正的 reload 功能,应该保持未定义。我将“真正的重新加载功能”定义为不会终止和重新启动服务或使服务更改其 PID 的重新加载。换句话说,systemd 只想反映存在哪些功能。

相反,您应该使用systemctl reload-or-restartwhich 将在存在时重新加载,如果不存在则重新启动。

从手册页...

   reload-or-restart PATTERN...
       Reload one or more units if they support it. If not, restart them
       instead. If the units are not running yet, they will be started.

   reload-or-try-restart PATTERN...
       Reload one or more units if they support it. If not, restart them
       instead. This does nothing if the units are not running. Note that,
       for compatibility with SysV init scripts, force-reload is
       equivalent to this command.
Run Code Online (Sandbox Code Playgroud)

因此:(1) 将 ExecReload 留空,(2) 使用systemctl reload-or-restart MYSERVICE和,(3) 您应该全部设置。

如果您确实尝试使用 ExecReload 来定义终止和重新启动服务的方法,它将有一个新的 PID 并且 systemd 会感到困惑。