从所有FIFO中读取完所有数据后,是否应该从FIFO块中读取数据? [英] Should a read from FIFO block after all the data was just read from that FIFO?

查看:877
本文介绍了从所有FIFO中读取完所有数据后,是否应该从FIFO块中读取数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在学习Linux中的管道编程,并且在理解管道/FIFO管理方面遇到困难.

I'm learning about pipe programming in Linux, and am having trouble understanding pipe / FIFO management.

我写了一个小程序,它打开了我创建的FIFO(在执行程序之前,我在终端中做了mkfifo newfifo).然后,我反复读取并转储我的字符缓冲区.我正在从另一个终端的cmd行中使用echo "message" > newfifo填充FIFO.

I wrote a small program which opens a FIFO I created (I did mkfifo newfifo in my terminal before executing the program). I then repeatedly read and dump my character buffer. I'm filling the FIFO using echo "message" > newfifo from another terminal's cmd line.

问题在于,当我写入FIFO时,我可以读取缓冲区中的数据,但随后读取不会再阻塞.我的理解是,当我从FIFO读取数据后,FIFO应该为空,并且读取应该阻塞.我是在考虑这个错误,还是在错误地管理FIFO?

The problem is that when I write to the FIFO, I can read that data in the buffer, but then the read doesn't block anymore. My understanding was that after I read the data from the FIFO, the FIFO should be empty and the read should block. Am I thinking about this wrong, or am I incorrectly managing the FIFO?

代码如下:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/types.h>

#define NEWPIPE "./newfifo"

void main()
{
  int great_success = 0; 
  int fd;
  char buffer[20];

  fd = open(NEWPIPE, O_RDONLY);

  while (1) {
    great_success = read(fd, buffer, 20);

    if (great_success < 0) {
      printf("pipe failed\n");
    } else {
      printf("buffer : %s\n", buffer);
      printf("great_success = %d\n", great_success);
      great_success = 0;
    }
  }
}

推荐答案

您对fifos的工作方式的理解不正确.它们很像管道:如果写端关闭(echo命令已终止),则读端将读取文件结尾(EOF),即返回0.

Your understanding of how fifos works is incorrect. They are much like pipes: if the write end is closed (the echo command has terminated), the read end will read end-of-file (EOF), i.e. return 0.

请注意,当您打开fifo时,不会读取表示正在阻塞.阻塞的系统调用是open()系统调用,如 http://linux.die中所述. net/man/4/fifo

Note that when you open the fifo, it isn't read that is blocking. The blocking system call is the open() system call, as explained in http://linux.die.net/man/4/fifo

这篇关于从所有FIFO中读取完所有数据后,是否应该从FIFO块中读取数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆