D
D
Dmitry Logvinenko2019-02-13 11:24:35
linux
Dmitry Logvinenko, 2019-02-13 11:24:35

How to start a process from a Python service that will continue to live after the service dies?

I made a service in Python that can start and kill third party processes (using Popen). But there is one small problem: when a service ( systemctl stopor just a killprocess) exits, it takes running processes with it to the grave.
A couple of examples

  • pyservice.service(unit-file):
    [Service]
    ExecStart=/opt/pyservice/service.py
  • service.py:
    ...
    subprocess.Popen('server.sh')
    ...
  • server.sh:
    /usr/bin/java -server -jar ./Application.jar &
What is happening in our kingdom?
I am running multiple instances server.shwith pyservice.
ps -aef --forestshows the expected tree:
python3.6 /opt/pyservice/service.py
\_ [server.sh] <defunct>
/usr/bin/java -server -jar ./Application.jar 
/usr/bin/java -server -jar ./Application.jar

If I put service.py, Application.jarit will also end.
What do we want?
So that after kill service.pyor restarting pyservice, our launched through it server.shand its contents continue to rustle.
What have I already tried to do?
Various combinations of os.system, subprocess.Popen, nohup, &and their arguments.
What am I doing wrong?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander, 2019-02-13
@NeiroNx

the easiest way is to use the system command screen
when the screen itself dies - the running process continues to work

D
Dmitry Shitskov, 2019-02-13
@Zarom

Try a double fork:
https://stackoverflow.com/a/41433401
Example. The ping will continue to work after the parent terminates:

import os, time, sys
import subprocess

time.sleep(1)

forked_pid = os.fork()

if forked_pid == 0:
  print("I am child!")
  subprocess.Popen(['ping','-c','10','localhost'])
  print("Child Quit")
else:
  print("I am parent!")
  time.sleep(2)
  print("Parent Quit")

sys.exit()

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question