How to restart a systemctl service from within the process

Colin Watson cjwatson at ubuntu.com
Sun Nov 22 18:44:10 UTC 2020


On Sun, Nov 22, 2020 at 09:45:50AM +0000, Colin Law wrote:
> I have a service (a nodejs process running node-red) and want it to
> self-restart.  The obvious way appears to be to invoke
> systemctl restart theservice
> but I am concerned about the fact that the process running the
> systemctl command will itself be killed as part of the restart.  It
> does seem to work but that is not a guarantee that there is not a
> possible race condition that could cause it to fail.  I am hoping that
> someone can reassure me that there is not actually a problem doing
> this.

"systemctl restart" is implemented as sending a single D-Bus method call
(RestartUnit) to pid 1, so I believe this will indeed currently work
since it's pid 1 that's doing the actual restart work and all that the
systemctl process is doing after sending the request is waiting for it
to respond.  I don't think this implementation detail is officially
documented or guaranteed, though, so it might change in future; and
there seems some possibility that error handling might be a bit weird -
for example if attempting to stop the unit manages to kill the systemctl
process but fails to kill the nodejs process, then I don't think your
proposed arrangement would notice that.

If I were implementing this, then my first inclination would be to give
the process a way to re-exec itself, or else fork a new version of
itself and use sd_notify with MAINPID=... to hand over control to it
(see
https://unix.stackexchange.com/questions/202048/self-restarting-service-does-not-restart-with-systemd).
But if that weren't viable for some reason, then I'd be inclined to try
writing a "<your-service-name>-restart.service" unit file with
"Type=oneshot" and "ExecStart=/bin/systemctl restart
<your-service-name>.service", or something along those lines, and then
use "systemctl start <your-service-name>-restart.service".  It's a bit
twistier, and I haven't tested this approach, but I think either of
these approaches would result in more reliable error handling.

-- 
Colin Watson (he/him)                              [cjwatson at ubuntu.com]




More information about the ubuntu-users mailing list