简体   繁体   中英

bash. while loop with xargs kill -9

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?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM