I have a bash script to test how a server performs under load.
num=1 if [ $# -gt 0 ]; then num=$1 fi for i in {1 .. $num}; do (while true; do { time curl --silent 'http://localhost'; } 2>&1 | grep real done) & done wait
When I hit Ctrl-C, the main process exits, but the background loops keep running. How do I make them all exit? Or is there a better way of spawning a configurable number of logic loops executing in parallel?
Use signals to exit process from subshell This is the mechanism that allows you to exit a command line process by pressing ctrl-c. When you press ctrl-c in your terminal, an interrupt signal (SIGINT) is sent to the current process.
If you are executing a Bash script in your terminal and need to stop it before it exits on its own, you can use the Ctrl + C combination on your keyboard.
To interrupt it, you can try pressing ctrl c to send a SIGINT. If it doesn't stop it, you may try to kill it using kill -9 <pid> , which sends a SIGKILL. The latter can't be ignored/intercepted by the process itself (the one being killed). To move the active process to background, you can press ctrl z .
< Bash programming. Subshells are one way for a programmer to capture (usually with the intent of processing) the output from a program or script. Commands to be run inside a subshell are enclosed inside single parentheses and preceeded by a dollar sign: DIRCONTENTS=$(ls -l) echo ${DIRCONTENTS}
Here's a simpler solution -- just add the following line at the top of your script:
trap "kill 0" SIGINT
Killing 0
sends the signal to all processes in the current process group.
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