c++ - linux中管道之间的通信

标签 c++ linux pipe

我有两个函数 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。我不知道如何解决这个问题。需要更多帮助。

enter image description here

感谢您的帮助。

最佳答案

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

类似于mkfifo("/tmp/pipe", 0666) , 在你打开之前 /tmp/pipe在读者/作家中。

另请查看 fifo man page :

The kernel maintains exactly one pipe object for each FIFO special file that is opened by at least one process. The FIFO must be opened on both ends (reading and writing) before data can be passed. Normally, opening the FIFO blocks until the other end is opened also.

所以你现在的问题是,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 .

关于c++ - linux中管道之间的通信,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22714816/

相关文章:

c++ - 在 QAbstractItemView 中查找拖放操作的结束

c++ - 编译错误递归链表

linux - 如何处理异步套接字上所有可能的错误?

linux - 如何在虚拟控制台 (tty1) 中显示 linux printk() 消息

转到 crypto/ssh 包,stdoutpipe() io.Reader 的缓冲区限制是多少

python - 启动包含管道命令的子进程时找不到文件错误

c++ - 编译器在不需要时关心复制构造函数

c++ - 如何将带有 const 参数的 C++ 函数或 C++ 结构链接到 D 可执行文件?

linux - 如何使用 Gnuplot 4.6 和 AIX 7.2 修复 "Could not find/open font when opening font arial..."和模糊的 png?

linux - 尝试将管道命令放入 if 语句