2

I have code which runs a webcamera on a linux pc using the gst-launchcommand.

When I kill the process, the webcamera window does not turn off, but the program stops running. I want the webcamera window also to be closed. Can you help me on this?

import subprocess
import time
import os
import signal

cmd = "gst-launch-1.0 -v v4l2src ! video/x-raw,format=YUY2 ! videoconvert ! autovideosink"
process = subprocess.Popen(cmd, shell = True)
time.sleep(5)
#print(subprocess.Popen.pid)
#process.terminate()
os.kill(process.pid, signal.SIGKILL)
#process.kill()
Ivo
  • 3,890
  • 5
  • 22
  • 53
Mahima K
  • 85
  • 2
  • 11

2 Answers2

3

For me, the currently accepted answer will terminate the main program as well. If you experience the same problem and want it to continue, you will have to also add the argument preexec_fn=os.setsid to popen. So in total:

import os
import signal
import subprocess

process = subprocess.Popen(cmd, shell=True, preexec_fn=os.setsid)
os.killpg(os.getpgid(process.pid), signal.SIGTERM)

I got this from here: https://stackoverflow.com/a/4791612/11642492

semaj
  • 31
  • 3
2

Hope it will help you.

import os
import signal
import subprocess

process = subprocess.Popen(cmd, shell = True)
os.killpg(os.getpgid(process.pid), signal.SIGTERM)
Adam Strauss
  • 1,889
  • 2
  • 15
  • 45
  • Thanks it worked, what is the difference between os.kill() and os.killpg()? – Mahima K Oct 24 '19 at 09:21
  • @MahimaK actually here in os.killpg() all pg(process group) is going to be killed. For that, you should attach a session id to the parent process of the spawned/child processes, in your case it is shell. This will make it the group leader of the processes. So now, we are giving a signal to the parent of the processes and parent process will pass it to all child processes. – Adam Strauss Oct 24 '19 at 09:45
  • Oh ok, I am writing a flask app that has subprocess in it, but the os.killpg command exits the program, I want the program to run even after executing this. How can you achieve that? – Mahima K Oct 30 '19 at 03:58