如何将消息写入 FIFO 并同时从另一个进程读取它

How to write messages into a FIFO and read it from another process simultaneously

在Unix系统中,我只知道我们可以使用FIFO文件来实现两个进程之间的通信,并且我已经在C项目中进行了测试。

现在我想知道我们是否可以做这样的事情:

我已经尝试了以下方法,但它不起作用。在一个终端上:

mkfifo fifo.file
echo "hello world" > fifo.file

在另一个终端上:

cat fifo.file

现在我可以看到 "hello world"。但是,这两个过程都立即完成,我无法继续输入/阅读 fifo.file

来自info mkfifo

Once you have created a FIFO special file in this way, any process can open it for reading or writing, in the same way as an ordinary file. However, it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it. Opening a FIFO for reading normally blocks until some other process opens the same FIFO for writing, and vice versa.

因此您应该在一个进程(终端)中打开文件进行读取:

cat fifo.file

并在另一个进程(终端)中打开文件进行写入:

echo 'hello' > fifo.file
上面示例中的

cat 在文件(输入)结束时停止从文件中读取。如果你想继续从文件中读取,使用tail -F命令,例如:

tail -F fifo.file

如果要写入并同时将字符串发送到管道的另一端,请按如下方式使用cat

cat > fifo.file

在您键入时,字符串将被发送到管道的另一端。按Ctrl-D停止写入。