Use Python to Restart All the Process

Use Python to Restart All the Process

My platform is ROS Ubuntu in Raspberry Pi 2. I started a shell script by running python node to restart all process. However, when I kill the python node, everything started by the python node is also killed.

Python:

 from subprocess import call
 call(['bash', 'run.sh'])

My questions:

  1. Is there any way to kill and restart the process in python?
  2. Is it possible to kill the python node but keep alive those processes that were started by that python node?
5

1 Answer

Suppose we run some kind of python script via python stuff.py. We can easily find it's PID via pgrep

$ pgrep -f stuff.py                                                                                         
7573

And kill with pkill in a similar fashion.

$ pkill -f stuff.py

If you want to kill only the child process, and not script itself, then we need to find out the children. ps command allows printing processes with PPID ( parent PID) . So if you know the parent ( your python script) then you know the children too.

$ ps -e -o args,pid,ppid  | grep $(pgrep -f run_bash.py ) | grep -v grep                                       
python run_bash.py           8186  4021
watch ls                     8187  8186

Here my python script runs watch ls command. I can kill 8187 to close watch ls and let python script move on to the other things.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Sarah Jenkins
Author

Sarah Jenkins

Sarah Jenkins is a veteran tech journalist with over 12 years of experience covering artificial intelligence, mobile innovations, and digital ethics. Her insights have appeared in leading technology publications worldwide.