FIFO,在BASH/SH中带有一个READER和多个WRITER [英] FIFO with one READER and multiple WRITER in BASH/SH
问题描述
我有一个命名管道(FIFO)说:'MY_FIFO'
I have one named pipe (FIFO) say : 'MY_FIFO'
一个进程从多个进程读取fifo以获得指令.
One process reads the fifo from multiple processes to get instructions.
(1)阅读器bash脚本:
(1) reader bash script:
while read LINE < 'MY_FIFO'
do
# process line
done
(许多)作家bash脚本:
(many) writer bash script:
while [ 1 ]
do
INSTRUCTION = # get an instruction
echo $INSTRUCTION > 'MY_FIFO'
done
当我们有1位作家或作家不同时写作时,此方法可以很好地将指令传递给读者.但是,如果我们有很多作家同时写作,那么读者就会从最早写入FIFO的那个人那里得到第一条消息,然后挂起等待输入,而不是获取下一条指令.
This works fine to pass instructions to the reader when we have 1 writer or that the writers don't write at the same time. But if we have many writers writing at the same time, the reader gets the first message from whoever was the very first to write to the FIFO, and then hangs waiting for input instead of fetching the next instruction.
在幕后发生了什么,使我无法让多个作者写同一张fifo?他们会覆盖对方的指令吗?
What happens behind the scene that prevents me from having multiple writers write to the same fifo? Are they overwriting each other's instructions?
在写fifo之前,有没有办法让我测试读者是否已准备好从fifo进行读取?
Is there a way for me to test that the reader is ready to read from fifo before writing to the fifo?
推荐答案
一个问题是,当编写者编写其消息时,它将关闭管道,然后您的读者将退出该循环.当多个进程同时写入时,管道中还会出现乱码消息.
One problem is that when the writer has written its message, it closes the pipe and then your reader will exit that loop. You will also get garbled messages in the pipe when more than one process writes at the same time.
您可以尝试使用此方法.它在写入时使用 flock
锁定管道:
You could try something this instead. It uses flock
to lock the pipe while writing to it:
阅读器
#!/bin/bash
while [[ 1 ]]
do
IFS= read -r LINE < MY_FIFO
echo reader got "$LINE"
done
writers -请注意,这将首先打开管道,然后等待锁成功,最后写入消息:
writers - Note that this opens the pipe first, then waits for the lock to succeed and finally writes the message:
#!/bin/bash
# getting instructions from stdin for demo purposes
while IFS= read -r INSTRUCTION
do
echo Sending "$INSTRUCTION"
# advisory lock of the pipe when writing
flock MY_FIFO echo "$INSTRUCTION" > MY_FIFO
done
可选的 writers -创建一个锁定文件,直到实际持有该锁定后才打开fifo.
Optional writers - This creates a lockfile and does not open the fifo until the lock is actually held.
#!/bin/bash
while IFS= read -r INSTRUCTION
do
echo Sending "$INSTRUCTION"
{
flock 9
echo "$INSTRUCTION" > MY_FIFO
} 9> MY_FIFO.lck
done
这篇关于FIFO,在BASH/SH中带有一个READER和多个WRITER的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!