I've got a couple python scripts which I start collectively from a shell script as follows:
#!/bin/bash
python prog1.py &
python prog2.py &
python prog3.py
Since I am developing I often want to stop these processes. I normally do so by hitting ctrl+C, but unfortuntaly a couple python programs keep (zeromq) sockets open. This means I then have to manually find them (I use lsof -i), and kill them using the PID.
So I'm looking for an easier way of automatically killing those python processes from the shell when I hit ctrl+C. On another thread here on Stackoverflow I found some code which supposedly should do what I need. I just don't understand anything about the code and how I could adjust it to my needs.
Would anybody be so kind to help me out here?
cat >work.py <<'EOF'
import sys, time, signal
signal.signal(signal.SIGINT, signal.SIG_DFL)
for i in range(10):
time.sleep(1)
print "Tick from", sys.argv[1]
EOF
chmod +x work.py
function process {
python ./work.py $1
}
process one &
wait $!
echo "All done!"
ctrl c is used to kill a process. It terminates your program. ctrl z is used to pause the process. It will not terminate your program, it will keep your program in background.
Assuming it's running in the background, under your user id: use ps to find the command's PID. Then use kill [PID] to stop it. If kill by itself doesn't do the job, do kill -9 [PID] . If it's running in the foreground, Ctrl-C (Control C) should stop it.
The exit() function is used to terminate program execution and to return to the operating system. The return code "0" exits a program without any error message, but other codes indicate that the system can handle the error messages. Syntax: void exit(int return_code);
Let the bash script catch SIGINT, and have it kill everything in the current process group:
intexit() {
# Kill all subprocesses (all processes in the current process group)
kill -HUP -$$
}
hupexit() {
# HUP'd (probably by intexit)
echo
echo "Interrupted"
exit
}
trap hupexit HUP
trap intexit INT
python prog1.py &
python prog2.py &
python prog3.py &
wait
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With