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

标签 linux shell unix cat fifo

在 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/

相关文章:

在Linux中将物理地址转换为虚拟地址并读取其内容

linux - 停止在使用 sudo 运行的脚本中间成为 root

bash - 在 Unix 中将 zip 转换为存储压缩

linux - 为什么我的 Perl 脚本在 "~/"上失败,但适用于 "$ENV{HOME}"?

linux - 运行 Rsync 命令的问题

linux - 使用 tar 命令将文件拆分为特定大小

c - GCC Linux C - 找不到编译对象头

c - 指向函数名称、输入参数、?

linux - sed 在替换某些正则表达式时行为不端

shell - 在shell脚本中映射文件的对应值