FIFO with one READER and multiple WRITER in BASH/SH

僤鯓⒐⒋嵵緔 提交于 2021-01-29 07:42:55

问题


I have one named pipe (FIFO) say : 'MY_FIFO'

One process reads the fifo from multiple processes to get instructions.

(1) reader bash script:

while read LINE < 'MY_FIFO'
do
 # process line
done

(many) writer bash script:

while [ 1 ]
do
  INSTRUCTION = # get an instruction
  echo $INSTRUCTION > 'MY_FIFO'
done

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.

What happens behind the scene that prevents me from having multiple writers write to the same fifo? Are they overwriting each other's instructions?

Is there a way for me to test that the reader is ready to read from fifo before writing to the fifo?


回答1:


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.

You could try something this instead. It uses flock to lock the pipe while writing to it:

reader

#!/bin/bash

while [[ 1 ]]
do
    IFS= read -r LINE < MY_FIFO
    echo reader got "$LINE"
done

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

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


来源:https://stackoverflow.com/questions/64486022/fifo-with-one-reader-and-multiple-writer-in-bash-sh

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!