Search code examples
pythonsystemdnohup

How to make a child process survive service shutdown?


script1.py:

#do somthing
os.system('nohup python3 -u script2.py {} {} >> {}.out &'.format(xxx, yyy, zzz))
#do somthing

script2.py: this scipt always run with loop.run_forever()

When script1 run as a service, this script runs script2 correctly. But if i kill Script1 with 'kill pid' command, Script2 will also be killed automatically, which I do not want and I want Script2 to continue working.

Edit: I use systemd for running script1.py


Solution

  • If you want child processes you start to not be killed by systemd, change the KillMode configured for your service. Thus, in your service file:

    [Service]
    KillMode=process
    

    The default value is KillMode=control-group, such that systemd kills everything in the cgroup it created for the service; and nohup doesn't know anything about cgroups.