用bash在后台拖曳多个文件

时间:2014-07-15 01:08:57

标签: bash automation background-process tail watch

我从未在bash中写过这么激烈的东西。基本上,我想并行运行有限数量的数据导入脚本。为此,我需要知道何时终止以便开始下一个。但是,我不确定如何并行执行此操作。以下工作同步:

# watch the outputfile for "DONE!"
tail -f $outputfile | while read OUTPUT
do
  if [[ "${OUTPUT}" == *"DONE!"* ]]
  then
    runNextScript
  fi
done

如何异步运行?

1 个答案:

答案 0 :(得分:1)

  

基本上,我想在中运行有限数量的数据导入脚本   平行。为此,我需要知道何时终止   开始下一个。

这样做的一种方法是创建一个包含与最大并发脚本数量一样多的令牌的fifo。

然后,在启动任务之前,首先使用令牌,实际启动任务,最后将令牌放回到fifo中。这样,当达到最大工作脚本数时,下一个工作脚本将被阻止,直到令牌可用。

不清楚?这是一个概念证明(你明确地必须适应你的需求!):

  • master.sh
#!/bin/bash

rm -f fifo
mkfifo fifo

exec 3<>fifo

# Simulate 26 tasks
tasks=$(exec echo {a..z})

#insert 5 tokens in the fifo
#that is at max 5 worker working at the same time
for i in {1..5}; do
    (echo T >&3; echo Insert token) &
done

# launch the tasks when a token is available
for i in $tasks; do
    read <&3
    ( ./worker.sh $i; echo T >&3 ) &
done

wait
  • worker.sh(不太感兴趣:模拟做一些事情)
  

#!/斌/庆典

# simulate doing some stuff
S=$(( RANDOM % 10 ))
echo "$(exec date +%s) PID$$ doing task $1 for $S"
sleep $S

以下是会话的成绩单:

sh$ ./master.sh 
Insert token
Insert token
Insert token
Insert token
Insert token
1405456428 PID3039 doing task a for 0
1405456428 PID3041 doing task b for 0
1405456428 PID3046 doing task e for 5
1405456428 PID3043 doing task c for 5
1405456428 PID3045 doing task d for 8
1405456428 PID3055 doing task f for 4
1405456428 PID3057 doing task g for 0
1405456428 PID3066 doing task h for 6
1405456432 PID3070 doing task i for 2
1405456433 PID3074 doing task j for 3
1405456433 PID3077 doing task k for 0
1405456433 PID3082 doing task l for 9
1405456434 PID3086 doing task m for 3
1405456434 PID3089 doing task n for 5
1405456436 PID3094 doing task o for 7
1405456436 PID3097 doing task p for 7
1405456437 PID3102 doing task q for 2
1405456439 PID3106 doing task r for 3
1405456439 PID3109 doing task s for 3
1405456442 PID3114 doing task t for 7
1405456442 PID3118 doing task u for 5
1405456442 PID3121 doing task v for 7
1405456443 PID3126 doing task w for 9
1405456443 PID3129 doing task x for 3
1405456446 PID3134 doing task y for 9
1405456447 PID3138 doing task z for 1

当工人的总“工作时间”为113秒时,总执行时间约为20秒。如果我没错,那个因素5对应于同时工作的5名工人。