Systemd – Child Processes Killed When Main Process Exits

process-managementsystemdsysvinit

Don't normally post here but I am ripping my hair out over this one.
I have a Python script that forks when it launches, and is responsible for starting a bunch of other processes. This script used to be launched at startup via sysvinit, but recently I upgraded to Debian Jessie so have adapted it to launch via systemd.

Unfortunately, I'm running into an issue I can't work out. When you launch the script directly in a user shell, it launches it's child processes correctly, and when the script exits the child processes are orphaned and continue to run.

When launched Via systemd, if the parent process exits, the children all exit too (Well, the screens that they launch in die and appear as Dead).

Ideally I need to be able to restart the parent script without killing all the child processes, is there something that I am missing?

Thanks!

[Unit]
Description=Server commander
After=network.target

[Service]
User=serveruser
Type=forking
PIDFile=/var/Server/Server.pid

ExecStart=/var/Server/Server.py
ExecStop=/bin/kill -s TERM $MAINPID

[Install]
WantedBy=multi-user.target

Edit:

It's probably relevant for me to point out that the Python script is essentially a 'controller' for its child processes. It starts and stops servers in GNU screens as requested from a central server. It is normally always running, it doesn't spawn services and exit.

There are cases however where I would like to be able to reload the script without killing child processes, even if that means the processes are orphaned off to pid 1. In fact, it wouldn't even matter if the Python script started off processes as a parent process, if that is even possible.

A better explanation of how it works:

  • systemd spawns Server.py
  • Server.py forks and writes the pid file for systemd
  • Server.py then spawns server processes in gnu screen based on its instructions
  • Server.py continues to run to perform any restarts requested from the server

When launching without systemd, Server.py can be restarted and the GNU screens it launches are unaffected. When launching with systemd, when Server.py shuts down, instead of those screen processes being orphaned off to pid 1, they are killed.

Best Answer

I managed to fix this simply by setting KillMode to process instead of control-group (default). Thanks all!

Related Question