0

How to use subprocess to terminate a program which is started at boot? I ran across this question and found wordsforthewise's answer and tried it but nothing happens.

Wordsforthewise' Answer:

import subprocess as sp

extProc = sp.Popen(['python','myPyScript.py']) # runs myPyScript.py 

status = sp.Popen.poll(extProc) # status should be 'None'

sp.Popen.terminate(extProc) # closes the process

status = sp.Popen.poll(extProc) # status should now be something other than 'None' ('1' in my testing)

I have a program /home/pi/Desktop/startUpPrograms/facedetection.py running at boot by a Cronjob and I want to kill it from a flask app route like this.

Assigning program name to extProc = program_name would work? If yes how to assign it?

@app.route("/killFD", methods=['GET', 'POST'])
def killFaceDetector():
    #kill code goes here.
Shyam3089
  • 459
  • 1
  • 5
  • 20
  • Why wouldn't you just modify the cronjob not to run at boot? Also, if it started at boot it's probably a daemon and not a cronjob. – l'L'l Mar 09 '20 at 08:08
  • I want it run at boot. I need an option to kill it when needed from a Flask app. I have a noIR camera and web camera connected to Raspberry pi. When I start webcam I want to kill the face detection program which is using noIR cam. – Shyam3089 Mar 09 '20 at 08:19
  • If you know the name of the process you could do `pkill ` and that should normally do it. – l'L'l Mar 09 '20 at 08:36

1 Answers1

2

Since you say the program is run by cronjob, you will have no handle to the program's PID in Python.

You'll have to iterate over all processes to find the one(s) to kill... or more succinctly, just use the pkill utility, with the -f flag to have it look at the full command line. The following will kill all processes (if your user has the permission to do so) that have facedetection.py in the command line.

import os

os.system('pkill -f facedetection.py')
AKX
  • 152,115
  • 15
  • 115
  • 172