我有一个bash脚本想要并行执行一些工作,我通过将每个作业放在一个在后台运行的子 shell 中来完成此任务。尽管同时运行的作业数应处于一定限制下,但我可以通过先在FIFO中放入几行来实现,然后在派生子Shell之前,需要父脚本从该FIFO中读取一行。只有在获得一行之后,它才能派生子shell。到目前为止,一切正常。但是,当我尝试从子 shell 中的FIFO读取一行时,即使FIFO中显然有更多的行,似乎只有一个子 shell 可以获取一条线。所以我想知道为什么即使FIFO中有更多行,其他子 shell 也无法读取行。

我的测试代码如下所示:


#!/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子进程在那里被阻止,直到我发出:
回声>/tmp/fy_u_test2.fifo

最佳答案

您对fifo的写入是否可能会进行一些缓冲?如果您有可用的缓冲区,可以尝试在回显之前添加前缀吗?我真的不知道如何在这里发生,但症状适合,所以值得一试。

关于linux - Linux FIFO中的数据似乎丢失了,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2712093/

10-13 07:34