繁体   English   中英

Linux中管道之间的通信

[英]Communication between pipes in linux

我有两个函数writer()reader() 我正在从writer()函数将消息写入管道,并从reader()函数读取消息。 我面临的问题是消息正在管道中写入,但没有被读取。 也许在打开管道进行读取时存在问题。 代码是:

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

using namespace std;

//edit
int fifo = mkfifo("/tmp/mypipe", S_IWUSR | S_IRUSR | S_IRGRP | S_IROTH);

void writer()
{
    char message[] = "this is a message";
    int fd;
    fd = open("pipe" , O_WRONLY);
    write(fd , message , sizeof(message));
    cout<<"message wrote: "<<message<<"\n";     // gives output 
}                                               // message wrote: this is a message

void reader()
{
    char buffer[100];
    int fd;
    fd = open("pipe" , O_RDONLY);
    read(fd , buffer , 100);
    cout<<"message is: "<<buffer<<"\n";     // gives output
}                                           // message is:

int main()
{
    writer();
    reader();
    return 0;
}

我已经调试了它,我想问题是,fifo的创建不正确。 我不知道该如何解决。 需要更多帮助。

在此处输入图片说明

感谢您的任何帮助。

我的猜测是您没有以正确的方式创建管道。 看看mkfifo手册页 对于umask值,请查看umask手册页

mkfifo("/tmp/pipe", 0666) ,然后在读取器/写入器中打开/tmp/pipe

还请看一下fifo手册页

内核为每个至少由一个进程打开的FIFO特殊文件维护一个管道对象。 必须先在两端打开FIFO(读取和写入),然后才能传递数据。 通常,打开FIFO块,直到另一端也打开。

因此,您的问题是, open(..., O_WRONLY)阻塞,直到读者打开文件为止。

要尝试,只运行阅读器,然后使用echo "test" > /tmp/pipe

更新:

或使用线程,我只是尝试了一下。

int main() {
    mkfifo(fifo_name.c_str(), 0666);
    std::thread w(writer);     
    std::thread r(reader); 
    w.join();
    r.join();
    unlink(fifo_name.c_str());
    return 0;
}

您还必须#include <thread> ,添加此编译器标志: -std=c++0x ,并将以下库添加到链接器: -lpthread

确保检查函数调用的返回值,因为它们可以告诉您问题出在哪里。

包括errno.h:

#include <errno.h>
#include <string.h>

并在从写入或读取打开尝试中获得错误返回时检查errno:

fd = open("pipe" , O_WRONLY);
if (fd < 0)
{   
    cout << "writer open failed: " << errno << "(" << strerror(errno) << ")\n";
    /* exit */
}   

另一个答案是,您没有使用mkfifo(),因此您正在创建一个典型的文件(该文件也可以工作,但如果不提供O_CREAT和mode参数,则可能会失败)。

它与posix中命名管道的工作方式有关。 如果已经有人从中读取内容,则只能在其中写入内容。 如果没有,您的write()操作将被阻止,直到有人不读为止。

最简单的解决方案是

  1. 您使用了非阻塞I / O
  2. 您在不同的进程(线程)中实现了读取器和写入器,并在写入器之前调用读取器。

暂无
暂无

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

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