0

I'm using a subprocess to run a command in terminal. I want to terminate the process when an event occurs by using the .terminate() function, however this doesn't seem to work.

 pipeline = "gst-launch-1.0 \
            nvcompositor name=comp \
            sink_0::xpos=0 sink_0::ypos=0 sink_0::width=2560 sink_0::height=720 sink_0::zorder=1 sink_0::alpha=1\
            sink_1::xpos=0 sink_1::ypos=0 sink_1::width=2560 sink_1::height=720 sink_1::zorder=2 sink_1::alpha=0.1\
            ! 'video/x-raw(memory:NVMM),format=RGBA' ! nv3dsink    \
            v4l2src device=/dev/video2 ! video/x-raw,format=YUY2,width=2560,height=720,framerate=30/1 ! nvvidconv ! 'video/x-raw(memory:NVMM),format=RGBA' ! comp.sink_0    \
            videotestsrc ! videoconvert ! video/x-raw,format=RGBA ! nvvidconv ! 'video/x-raw(memory:NVMM),format=RGBA,width=2560,height=720' ! comp.sink_1"


camera = subprocess.Popen(pipeline, shell=True)

camera.terminate()
print("terminated")

It never prints out terminated and the process continues running

Chealsie
  • 33
  • 6
  • What does your process table look like? On linux, the output of `ps -ef | grep python` should print all processes with "python" in their name (including this command). By using the `name` argument of the `Popen` method, you will be able to easily identify your subprocess and its state. – jacob Oct 12 '21 at 17:11
  • How do I set the `name` argument? I tried ` camera = subprocess.Popen(pipeline, shell=True, name="videostream")` but I got an error `unexpected keyword argument 'name'` – Chealsie Oct 12 '21 at 17:37
  • Sorry, you are correct, that should raise an argument error. I was confusing subprocess with multiprocess. To create a parallel process in multiprocess, you would call `camera = multiprocess.Process(target, name)` then camera.start(). For more on the difference between the two, see: https://stackoverflow.com/a/13607111/9403538 – jacob Oct 12 '21 at 17:59
  • In regard to subprocess, it seems the preferred invoking is the `run` method. Is there a specific reason you are using `Popen` instead? My guess though is that you are starting up some type of camera device. The device runs and never returns 0 from the terminal and your program is actually hanging on the call to `Popen`. `camera.terminate()` is likely not even getting called. – jacob Oct 12 '21 at 18:17

1 Answers1

0

This post was the answer I was looking for How to kill a subprocess in python

    camera = subprocess.Popen(pipeline, shell=True, preexec_fn=os.setsid)

      os.killpg(os.getpgid(camera.pid), signal.SIGTERM)

Kills the process properly

Chealsie
  • 33
  • 6