Reputation: 1
I have a list of IP addresses and I have to run a command for every single IP address.
I did it with this code:
array=($(</tmp/ip-addresses.txt))
for i in "${array[@]}"; do
./command start $i &
done
Now, the list of IP addresses is constantly refreshed every 2 minutes and I need to kill every command that is no longer with the new IP addresses. Practically, the command needs to be executed again every 2 minutes with the refreshed IP addresses and all the another old IP needs to be killed.
How can I do that?
Upvotes: 0
Views: 264
Reputation: 5972
Your script would be changed like:
#!/bin/bash
GAP=120
while :
do
#Do your stuff here
sleep $GAP
done
exit 0
After two minutes it would read from refreshed file
Upvotes: 0
Reputation: 20980
A simple workaround: (Not tested)
sleep_delay=120 # 2 mins
while true; do
(
array=($(</tmp/ip-addresses.txt))
for i in "${array[@]}"; do
./command start $i &
done
sleep $(( sleep_delay + 2 )) # 2 can be any number >0
) & PPID=$!
sleep $sleep_delay
pkill -9 -p $PPID
done
Note: I have not optimized your code, just added a wrapper around your code.
EDIT:
Edited code to satisfy requirement that the old processes should not be killed, if the IP is still same.
NOTE: I haven't tested the code myself, so be careful while using the kill command. You can test by putting echo
before the kill
statement. If it works well, you can use the script...
declare -A pid_array
while true; do
array=($(</tmp/ip-addresses.txt))
for i in `printf "%s\n" ${!pid_array[@]} | grep -v -f <(printf "%s\n" ${array[@]})`; do
kill -9 ${pid_array[$i]} # please try to use better signal to kill, than SIGKILL
unset pid_array[$i]
done
for i in "${array[@]}"; do
if [ -z "${pid_array[$i]}" ]; then
./command start $i & pid_array[$i]=$!
fi
done
sleep 120
done
Upvotes: 2