循环线程时bash [英] bash while loop threading

查看:72
本文介绍了循环线程时bash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个while循环,它从$hosts

i have a while loop reading lines from a $hosts

while read line
do
    ip=$line
    check
done < $hosts

我的问题是我可以使用某种方法来加快速度,还是一次在10台主机上运行检查,并且每笔检查都在不同的IP上并在检查完$host中的所有IP后完成? 谢谢

my question is can I use some way to speed this up or run the check on 10 hosts at a time and each check is on a different IP and finish when all IP in $host have been checked? Thanks

推荐答案

您可以通过&将任务发送到后台 如果您打算等待它们全部完成,则可以使用wait命令:

You can send tasks to the background by & If you intend to wait for all of them to finish you can use the wait command:

process_to_background &
echo Processing ...
wait
echo Done

如果要等待一个(或几个)特定任务,可以在后台启动给定任务的pid.

You can get the pid of the given task started in the background if you want to wait for one (or few) specific tasks.

important_process_to_background &
important_pid=$!
while i in {1..10}; do
    less_important_process_to_background $i &
done

wait $important_pid
echo Important task finished

wait
echo All tasks finished

不过请注意:由于后台进程将异步运行,因此它们可能会使输出混乱.您可能要使用命名管道来收集它们的输出.

On note though: the background processes can mess up the output as they will run asynchronously. You might want to use a named pipe to collect the output from them.

修改

如评论中所述,可能需要限制派生的后台进程.在这种情况下,您可以跟踪已启动了多少个后台进程,并通过命名管道与它们进行通信.

As asked in the comments there might be a need for limiting the background processes forked. In this case you can keep track of how many background processes you've started and communicate with them through a named pipe.

mkfifo tmp # creating named pipe

counter=0
while read ip
do
  if [ $counter -lt 10 ]; then # we are under the limit
    { check $ip; echo 'done' > tmp; } &
    let $[counter++];
  else
    read x < tmp # waiting for a process to finish
    { check $ip; echo 'done' > tmp; } &
  fi
done
cat /tmp > /dev/null # let all the background processes end

rm tmp # remove fifo

这篇关于循环线程时bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆