我有两个函数 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 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/