i have a bash script with a while loop background processes how can i stop the while loop without kill the process so by set a STOP flag
Note: my script is works if i use kill but with stop flag didn't work
this is a demo of my script(using Kill):
#!/bin/bash
background_processes=()
trap ctrl_c INT
ctrl_c() {
printf "\n[~] Killing background processes...\n"
for pid in "${background_processes[@]}"
do
kill $pid > /dev/null 2>&1
done
}
background_process() {
while true
do
sleep 5
printf "Hello World!\n"
done
}
start() {
for t in $(seq 1 10)
do
background_process &
background_processes+=(${!})
done
wait
}
printf "\n[I] Press 'ctrl+c' to kill background processes! \n"
start
This one works fine but the other method not work !
This is my same demo but with stop flag(not work!)
#!/bin/bash
STOP=0
threads=10
finished_threads=0
trap ctrl_c INT
ctrl_c() {
printf "\n[~] Stopping background processes...\n"
STOP=1
# here i was checking that all the background processes is finish
while true
do
if [[ $finished_threads == $threads ]]
then
break
fi
done
printf "\n[+] Done\n"
}
background_process() {
while true
do
sleep 5
printf "Hello World!\n"
if [[ $STOP = 1 ]]
then
((finished_threads++))
break
fi
done
}
start() {
for t in $(seq 1 $threads)
do
background_process &
done
wait
}
printf "\n[I] Press 'ctrl+c' to stop background processes! \n"
start
Can anyone tell me why this not works please ?
P.S: i am arabian btw so sorry if my English grammar is not good