Linux – When the operating system shuts down, how does a service manager know that it should sends SIGTERM and SIGKILL to its services

kernellinuxservicesshutdown

Reading one of Stephen's excellent replies,

When the operating system shuts down, processes are shut down using SIGTERM and SIGKILL, but those signals don’t come from the kernel (or not directly — calling kill() with a pid of 0 or a negative pid will result in the kernel sending the signal to a number of processes). They come from a service manager terminating its services and from various last-ditch-kill-everything application-mode programs that are part of the system management mechanism: e.g. the killprocs van Smoorenburg rc script, the killprocs OpenRC script, and the systemd-shutdown program.

When the OS shuts down,

  • How does a service manager know that it should terminates its services? Is the service manager notified by receiving SIGKILL or SIGTERM or some other signal from the kernel or some process?

  • Similarly how do various last-ditch-kill-everything application-mode programs that are part of the system management mechanism know that they should send out SIGTERM and SIGKILL?

Thanks.

Best Answer

A service manager knows it should terminate its services because the system administrator asked it to halt or reboot the system. When the administrator runs reboot, or the user chooses the corresponding option in his/her desktop environment, the init process is told to reboot (not the kernel, at this point). The init process takes care of everything it’s been configured to do before asking the kernel to actually reboot.

The last-ditch, kill-everything phase is part of the shutdown procedure: once the shutdown procedure has asked all running services to stop, it typically waits a short while, then kills any remaining processes.

The various init systems have different implementations of all this. With sysvinit, halting or rebooting is a runlevel transition, started by asking the running init to switch to the appropriate runlevel (see the telinit manpage for details). With systemd, it’s a target, which ends up running the systemd-halt service.