简体   繁体   English

管道中断,FIFO文件

[英]Pipe Broken, FIFO file

I'm trying a program to use FIFO file, but I'm getting Broken pipe as output. 我正在尝试使用FIFO文件的程序,但是我将“断管”作为输出。 Here is the code - 这是代码-

#include<iostream>
#include<stdlib.h>
#include<fcntl.h>
#include<stdio.h>
#include<string.h>
#include<unistd.h>
#include<sys/stat.h>
#include<sys/types.h>
using namespace std;
int main(int argc,char *argv[])
{
int fd; //stores file descriptor returnd from open
char buf[256];
if(argc<2||argc>3)
{
    cout<<"Invalid Arguments";
    return 1;
}

mkfifo(argv[1],0777);
if(argc==3)
{   
    cout<<"Writer\n";
    if((fd=open(argv[1],O_WRONLY))==-1)
    {
        perror("open");
        return 1;
    }
    write(fd,argv[2],strlen(argv[2]));
    sleep(10);
}
else
{   cout<<"Reader\n";
    if((fd=open(argv[1],O_RDONLY|O_NONBLOCK))==-1)
    {       
        perror("open");
        return 1;
    }

    read(fd,&buf,sizeof(buf));
    cout<<buf;

}
 close(fd);
 return 1;
 }

Output: Below Fifo is the name of the file and Hello is the content. 输出:Fifo下面是文件名,Hello是内容。

 ./a.out fifo hello & Writer ./a.out fifo Reader [1]+ Broken pipe 

I should get "Hello" as the output. 我应该得到“ Hello”作为输出。 Can anyone help? 有人可以帮忙吗?

Your write happens before you start your reader. 在开始阅读器之前,您的写操作发生了。 When you write to a pipe and it has no reader you get SIGPIPE. 当您在管道中写入数据而没有读取器时,您会得到SIGPIPE。

In this particular design, you need to handle SIGPIPE with retry logic. 在此特定设计中,您需要使用重试逻辑来处理 SIGPIPE。

The error you get is EPIPE and if you read a write manual you will see that you get EPIPE when 您得到的错误是EPIPE ,如果您阅读了write手册,则将在以下情况下看到EPIPE

fd is connected to a pipe or socket whose reading end is closed. fd连接到读数端关闭的管道或插座。

You get this error because you open the reading end of the pipe in non-blocking mode, which means the read call will not block and wait for data to be received, instead when the read call immediately return you close the pipe and exit the process. 之所以会出现此错误,是因为您在非阻塞模式下打开了管道的读取端,这意味着read调用将不会阻塞并等待接收数据,而是当read调用立即返回时,您将关闭管道并退出流程。

That means when you run the writer there is no one waiting for the data you write and you get the error. 这意味着当您运行编写器时,没有人等待写入的数据,并且会收到错误消息。

You need to run the read and the writer in opposite order: First the writer so it writes to the pipe, and then the reader to read the data from the pipe. 您需要以相反的顺序运行读取器和写入器:首先,通过写入器将其写入管道, 然后通过读取器从管道中读取数据。

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

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