1

I have two Python scripts on a Linux system. Let's call them service and killer. Service is run as a systemd service and killer as a script. Killer exists to perform certain tasks that can't be executed while service is running due to limited hardware resources and the will to keep the code simple.

What I need is to be able to start killer from service and then have killer kill service without dying itself (as a child process). How can I do that?

These are what I have tried so far (without success):

import subprocess
subprocess.call("killer.py")

import subprocess
subprocess.Popen(["killer.py"])

import sh
killer = sh.command("killer.py")
killer()
TheAG
  • 287
  • 1
  • 4
  • 10
  • 1
    Why do you need the kill-the-parent approach? Can't your service just spawn the child subprocess and exit? – Leon Jun 13 '17 at 07:04
  • Use `os.setsid()` in the child to disconnect from the parent. Get the process id (PID) of the parent using `os.getppid()` then use `os.kill()`. But really this is a poor design. – cdarke Jun 13 '17 at 07:05
  • @Leon: I need to be sure that the parent has really died. I thought killing it from outside would be more safe. – TheAG Jun 13 '17 at 07:10
  • Then you can perform all cleanup of the service process and then [replace it with the child process](https://stackoverflow.com/questions/6743567/replace-current-process-with-invocation-of-subprocess) – Leon Jun 13 '17 at 07:15
  • I'll try these suggestions a bit later today. Thanks so far! – TheAG Jun 13 '17 at 07:19
  • os.setsid() did not help, and I realized that replacing the process using os.execvp() might not be a good idea since the parent process is run as a systemd service. – TheAG Jun 13 '17 at 08:54
  • I ended up solving this by extending another systemd service that was already in the system. That service will now take care of starting killer when told so by service via D-Bus. That way, killer is no longer run as a child of service. – TheAG Jun 15 '17 at 10:02

0 Answers0