I have a python program that runs as a systemd user service. From that program, I launch external commands via subprocess.Popen(cmd, close_fds=True, start_new_session=True)
. My intention is for these new processes to stay running even after the parent service stops or restarts. This works completely fine when I run my program directly from the terminal, but when it's run as a systemd service, these processes get killed along with the parent program upon service restart.
I tried nohup
and double forking to no avail. I noticed that when double forking, the child process ends up having the systemd --user
as a parent, not init
as is the case when run simply from a terminal.
Am I missing something obvious? Is there a better way for a systemd service to launch external programs so that they're independent from it? Let me know if there's more info I should provide.
setsid(2)
call in the child process to create a new process group and session leader. – Stephen Harris Nov 08 '23 at 18:49start_new_session
argument calls setsid in the child process. Even calling it myself (as part of the double fork) didn't help... that is, not when run as a systemd service. – czert Nov 08 '23 at 21:05systemd-run
, or do you have a service file? If you have a service file, could you share its content? – aviro Nov 09 '23 at 10:31KillMode=process
solves my problem. – czert Nov 09 '23 at 14:07[Service]
section useType=forking
. Seeman systemd.service
for details, and also checkKillMode=
inman systemd.kill
. – Stewart Nov 15 '23 at 13:42