Issue
I want these 2 background processes to end, for example, after pressing CTRL + C, the only thing I found that could help, but this does not work correctly:
python3 script1.py &
python3 script2.py &
trap "trap - SIGTERM && kill -- -$$" SIGINT SIGTERM EXIT
Or is there another solution to run 2 scripts in parallel? Not necessarily in the background.
Solution
I would use something in the line of
function killSubproc(){
kill $(jobs -p -r)
}
./test.py one 10 &
./test.py two 5 &
trap killSubproc INT
wait
It is not limited to 2 subprocess, as you can see. The idea is simply to kill all (still running) process when you hit Ctrl+C jobs -p -r gives the process number of all running subprocess (-r limits to running subprocess, since some of your script may have terminated naturally ; -p gives process number, not jobs numbers)
And wait, without any argument, wait for all subprocess to end. That way, your main script is running in foreground while some subtasks are running. It still receives the ctrl+c. Yet, it terminates if all your subprocess terminates naturally. And also if you hit ctrl+c
Note: test.py is just a test script I've used, that runs for $2 seconds (10 and 5 here) and display $1 string each second (one and two here)
Answered By - chrslg Answer Checked By - Gilberto Lyons (WPSolving Admin)