简体   繁体   English

庆典。 while循环使用xargs kill -9

[英]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. 我有一个IP地址列表,我必须为每个IP地址运行一个命令。

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. 现在,IP地址列表每2分钟不断刷新一次,我需要删除不再使用新IP地址的每个命令。 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. 实际上,需要使用刷新的IP地址每2分钟再次执行该命令,并且需要杀死所有其他旧IP。

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. 编辑:如果IP仍然相同,编辑代码以满足不应该杀死旧进程的要求。
NOTE: I haven't tested the code myself, so be careful while using the kill command. 注意:我自己没有测试过代码,因此在使用kill命令时要小心。 You can test by putting echo before the kill statement. 您可以通过在kill语句之前放置echo来进行测试。 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 两分钟后,它将从刷新的文件中读取

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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