我有一个 bash 脚本,它想要并行执行一些工作,我通过将每个作业放在一个在后台运行的子外壳中来做到这一点。虽然同时运行的作业数量应该在一定范围内,但我首先将一些行放入 FIFO 中,然后在分叉子 shell 之前,父脚本需要从该 FIFO 中读取一行。只有在它得到一行之后,它才能分叉子shell。到目前为止,一切正常。但是当我试图从子shell中的FIFO读取一行时,似乎只有一个子shell可以得到一行,即使FIFO中显然有更多的行。所以我想知道为什么即使 FIFO 中有更多行,其他子外壳也无法读取一行。
我的测试代码如下所示:
#!/bin/sh
fifo_path="/tmp/fy_u_test2.fifo"
mkfifo $fifo_path
#open fifo for r/w at fd 6
exec 6<> $fifo_path
process_num=5
#put $process_num lines in the FIFO
for ((i=0; i<${process_num}; i++)); do
echo "$i"
done >&6
delay_some(){
local index="$1"
echo "This is what u can see. $index \n"
sleep 20;
}
#In each iteration, try to read 2 lines from FIFO, one from this shell,
#the other from the subshell
for i in 1 2
do
date >>/tmp/fy_date
#If a line can be read from FIFO, run a subshell in bk, otherwise, block.
read -u6
echo " $$ Read --- $REPLY --- from 6 \n" >> /tmp/fy_date
{
delay_some $i
#Try to read a line from FIFO, __ only one subshell succeeds the following line. __
read -u6
echo " $$ This is in child # $i, read --- $REPLY --- from 6 \n" >> /tmp/fy_date
} &
done
输出文件 /tmp/fy_date 的内容为:
Mon Apr 26 16:02:18 CST 2010
32561 Read --- 0 --- from 6 \n
Mon Apr 26 16:02:18 CST 2010
32561 Read --- 1 --- from 6 \n
32561 This is in child # 1, read --- 2 --- from 6 \n
在那里,我期待这样的一行:
32561 This is in child # 2, read --- 3 --- from 6 \n
但它永远不会出现,并且子#2 进程在那里被阻塞,直到我发出:
echo something > /tmp/fy_u_test2.fifo