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

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

问题描述

我有一个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 while 循环线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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