Monday, April 1, 2024

Prevent systemd from killing a child (sub-process) process on a service stop.

Because of cgroups, systemd knows which process belongs to which systemd unit even if it daemonizes (even to systemd/init). Therefore if you stop a systemd service unit (like a display manager), it’ll kill all processes which was spawned directly or indirectly by the display manager. To prevent this from happening, you need to play around with cgroup. 

Find the target PID which you want to avoid being killed. Then move it to another cgroup which systemd did not make (this is all about echoing it’s Pid to the new cgroup) --

 echo <pid> >> /sys/fs/cgroup/cgroup.procs

Now systemd has lost track of this process and you can stop the systemd service unit without systemd killing the process.