简体   繁体   English

FIFO 通道读取不正确

[英]FIFO channel reading incorrect

I have 2 unrelated processes.我有 2 个不相关的进程。 The first creates a FIFO channel and writes data to it.第一个创建一个 FIFO 通道并将数据写入其中。

testcomp:测试组合:

int main(int argc, char *argv[])
{
    int f1;
    char *send_buf = "Hello";
    char recv_buf[128] = {0};

    if (mkfifo("mk.fifo", S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH) == -1 && errno != EEXIST)
        error(0, errno, "mkfifo() error");

    f1 = open("mk.fifo", O_RDWR);
    perror("Opening ");

    printf("Sending string '%s'...\n", send_buf);
    write(f1, send_buf, strlen(send_buf));
    perror("Writing ");

    close(f1);
    return 0;
}

The second process should read data from a previously created channel.第二个进程应该从先前创建的通道读取数据。

test2comp: test2comp:

int main(int argc, char *argv[])
{
    int f2;
    char recv_buf[128] = {0};

    f2 = open("mk.fifo", O_RDONLY|O_NONBLOCK);
    perror("Opening ");

    read(f2, recv_buf, sizeof(recv_buf));
    perror("Reading ");

    printf("Received string '%s'\n", recv_buf);

    close(f2);
    return 0;
}

The problem is that the read data is empty .问题是读取的数据是空的 What could be the reason?可能是什么原因?

Console output:控制台输出:

在此处输入图片说明

A FIFO is just a named pipe. FIFO 只是一个命名管道。

It has to be open at both ends at the same time for communication to occur.它必须在在同一时间进行通信两端开口。 For example, your local man page should say something like例如,您的本地手册页应该说类似

The kernel maintains exactly one pipe object for each FIFO special file that is opened by at least one process.内核为至少一个进程打开的每个 FIFO 特殊文件维护一个管道对象。 The FIFO must be opened on both ends (reading and writing) before data can be passed. FIFO 必须在两端(读和写)都打开,然后才能传递数据。 Normally, opening the FIFO blocks until the other end is opened also.通常,打开 FIFO 会阻塞,直到另一端也打开。

What you did is:你所做的是:

  1. create a FIFO inode创建一个 FIFO inode
  2. open it for writing, implicitly creating a pipe associated with that inode打开它进行写入,隐式创建与该 inode 关联的管道
  3. write something into the pipe buffer even though nothing is reading from it yet将某些内容写入管道缓冲区,即使尚未从中读取任何内容
  4. close it again, destroying the pipe再次关闭它,破坏管道
  5. open a new pipe for reading, associated with the same (currently un-used) inode打开一个新管道进行读取,与相同的(当前未使用的)inode 相关联
  6. there's nothing in there, because it's a new pipe里面什么都没有,因为它是一个新管道

Normally I would expect the writer to block when opening the fifo, until a reader is present - I'm not sure why this didn't happen.通常我希望作者在打开 fifo 时阻塞,直到有读者出现 - 我不知道为什么没有发生这种情况。 You explicitly disabled this behaviour for the reader though by setting it to non-blocking.您通过将其设置为非阻塞来明确为阅读器禁用此行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM