Can a service application restart itself as a service?

Colin Watson cjwatson at ubuntu.com
Thu May 20 13:25:37 UTC 2021


On Thu, May 20, 2021 at 02:23:38PM +0200, Bo Berglund wrote:
> I am writing a service application for Linux.
> I want it to be able to restart itself, but I don't now the best way to do it.
> 
> To use cron to issue "systemctrl restart service" at a given time does not cut
> it because the application might be busy doing things at that time.
> It has to be in an idle state when it restarts.
> 
> The only thing I could figure out is if the application itself can restart the
> service from within when it has reached a safe idle spot.

The usual approach is for the application to install a handler for the
appropriate signal (probably SIGTERM) that just sets a flag, and to then
check the state of that flag at safe points in the main event loop and
shut down cleanly if appropriate.  A normal "systemctl restart" should
then do the right thing, at least provided that a clean shutdown doesn't
take too long.

Another common approach is to install a handler for some other signal
(conventionally SIGHUP or maybe SIGUSR1) that causes the application to
reload its state or re-exec itself from a safe point in its event loop
in a similar manner.

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




More information about the ubuntu-users mailing list