Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to kill all processes that were opened by a shell script upon ctrl + C?

Tags:

bash

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!"
like image 453
kramer65 Avatar asked Mar 21 '13 20:03

kramer65


People also ask

Does Ctrl C Terminate process?

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.

How do you kill a running shell script?

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.

How do I stop a script in C?

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);


1 Answers

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
like image 148
nneonneo Avatar answered Oct 14 '22 09:10

nneonneo