在 Unix 系统中,我只知道我们可以使用 FIFO 文件在两个进程之间进行通信,并且我已经在 C 项目中对其进行了测试。
现在我想知道我们是否可以做这样的事情:
- 打开两个终端。
- 使用一个将消息写入 FIFO 并使用 其他阅读。
- 当我在第一个终端的 FIFO 中放入东西时,第二个终端会立即显示它。
我已经尝试了以下方法,但它不起作用。在一个终端上:
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 停止写入。
关于linux - 如何将消息写入 FIFO 并同时从另一个进程读取它,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41057005/