命名管道 - 缓冲和阻塞

问题描述 投票:0回答:1

有人可以澄清命名管道(特别是在 Linux 中)在缓冲数据和阻塞方面的行为吗?

mkfifo pipe1

cat pipe1 # blocks until another process sends data

echo "hi" > pipe1 # running this in the other tty unblocks waiting "cat"

相反(这可以在之前在同一管道上进行的实验之后运行):

echo "ping" > pipe1 # blocks, seemingly until another process reads the data

cat pipe1 # unblocks the "echo" above, if run from another tty

这两个示例是否会阻塞,直到“另一端”被读/写 - 或者直到另一端“打开”为止? 管道是否有内部缓冲区(以便可以在没有阻塞的情况下进行进一步的写入)?

如果“读取”端的进程完成,而管道中尚未消耗一些数据(或者“写入”进程在完成之前发送更多数据) - 当下一个读取进程打开管道时,这些额外的数据是否会出现管子?

当写入过程完成并且我们消耗了它产生的所有数据时,我们是否在读取端识别出某种 EOF(即使稍后我们可以重用管道,从其他进程写入它)?

如果由于对机制的误解而导致问题不切题,我们深表歉意。请随意提供一些高级文档的链接。

linux unix io pipe
1个回答
0
投票
请注意,在您的第一个示例中,
    cat
  1. 并未“阻止”以下
    echo
    命令的执行,shell 负责该延迟,因为
    cat
    命令尚未完成。
    
    
  2. cat 最基本的用途是复制输入,您可以启动命令并“键入它”,直到完成您的想法。然后输入一个结束
Ctrl-D

字符来关闭

cat
的输入。为了使这一点更加具体,下面的示例将
cat
输入的输出重定向到文件中,即:
$ cat > myFile
here is some text
another line
Ctrl-D typed on its on line below, you won't see it in this transcript but `cat` will close its input stream
$ cat myFile
here is some text
another line
Ctrl-D typed on its on line below, you won't see it in this transcript but `cat` will close its input stream

    另一种允许您立即执行
  1. echo "hi" > pipe1

    cmd 而无需等待

    cat
    关闭的方法是通过在末尾附加
    &
    字符(在任何注释之前)“在后台”运行第一个命令字符),即
    猫管1 &

  2. 向标准输入发出输入结束信号的标准方法(通过
  3. >

    重定向或

    |
    (管道))是发送
    Ctrl-D
    字符。目前尚不清楚真正写入您的
    mkfifo pipe1
    的内容是什么,但如果发送一个
    Ctrl-D
    字符,std-in 流应该关闭。
    
    

  4. 您写道
  5. “如果“读取”端的进程完成,而管道中尚未消耗一些数据(或者“写入”进程在完成之前发送更多数据)“

  6. 我不太清楚你的意图是什么,但我认为我上面的观点
3)

涵盖了这个问题。管道和流设计为保持两端打开以进行读/写,直到发送/接收魔术字符 (

Ctrl-D
)。
您可能会发现一些程序不知道这样做,但这应该是一种罕见的情况。

© www.soinside.com 2019 - 2024. All rights reserved.