首页 » shell » 正文

shell “多线程”实现


#!/bin/bash
#使用方法 ./test.sh host1 host2
#注意,此处前提已经配置了ssh免登陆
#此程序规定了同时后台运行的程序个数为thread=2

host=$@

echo $host

function a_sub(){
sleep 3;
echo "Runing:ssh $1 \"date\""
ssh -n $1 "date"
}

tmp_fifofile="/tmp/$$.fifo"
mkfifo $tmp_fifofile
exec 6<>$tmp_fifofile
rm $tmp_fifofile

thread=2
for ((i=0;i<$thread;i++));do echo done>&6

for node in $host;do

read -u6

{
a_sub $node && {
echo "date on $node is finished"
}||{
echo "error"
}
echo >&6

}&

done

wait

exec 6>&-

exit 0

发表评论