0

I am trying to run a server in python. I need to start the service as a subprocess and after occurrence of an event, I need to stop the server and restart it. The problem is restarting it with a few modifications. The program does terminates the server but does not restart it

Simplified versions of code are below:

Server.py

import time
while(1):
   print("Executing...")
   time.sleep(1)

Start.py

import time
import subprocess
import signal
import os

def start_service():
   p = subprocess.Popen("python3 Server.py", shell = True)
   time.sleep(3)
   os.killpg(os.getpgid(p.pid),signal.SIGTERM)
   print("This is never printed!")

for i in range(3):
   start_server()

The output is:

xyz@xyzsystem:~/rougharea/$ python3 Start.py
Executing...
Executing...
Executing...
Terminated
xyz@xyzsystem:~/rougharea/$ 

It runs only once instead of running 3 times.

Also, print statement just after os.killpg() is not executed.

Can someone tell me what's wrong here?

Swappy
  • 11
  • 1
  • 1
    try replacing `os.killpg(os.getpgid(p.pid),signal.SIGTERM)` with `p.kill()` or `p.terminate()` – Nullman Apr 23 '20 at 11:22
  • 2
    You're killing the whole *process group*. Your own process is in that same group. Don't do that -- just kill the one process instead. (Who told you to use `killpg` in the first place?) – Charles Duffy Apr 23 '20 at 11:22
  • If https://stackoverflow.com/questions/4789837/how-to-terminate-a-python-subprocess-launched-with-shell-true is what told you to do it, see how it uses `os.setsid()`? That's critical; you can't leave it out: It's what makes the subprocess be in a different process group than your original script. – Charles Duffy Apr 23 '20 at 11:23
  • ...better, if you stop using `shell=True`, and make it `subprocess.Popen(['python3', 'Server.py'])`, you won't need `killpg()` at all. Or if for some reason you *really* want to keep the shell, you can make it `subprocess.Popen('exec python3 Server.py', shell=True)`. – Charles Duffy Apr 23 '20 at 11:24
  • @CharlesDuffy I should have read that.. It works fine now. Thanks! – Swappy Apr 23 '20 at 11:30

0 Answers0