我为糟糕的标题道歉,因为我不确定如何措辞。我必须在 C++ 中创建一个命名管道来进行分配。我了解命名管道的工作原理以及每一行应该做什么,但我遇到了一个问题,我和一个代码相同的 friend 无法解决。
这是一个简单的任务。我所要做的就是让一个程序创建命名管道并将用户输入的 char 数组放入其中。第二个程序(在它自己的终端中)只是从管道中读取 char 数组并将其输出到终端中。
在下面第 11 行的第二个程序中(c = open("/tmp/myfifo", O_RDONLY);),该程序似乎从未运行过该行。当我在终端中运行它时,什么也没有发生,它只是停在那里,就好像它处于死锁状态一样。我的 friend 没有这个问题,我们不知道是什么原因造成的。我使用默认终端在 Virtual Box 中的 Ubuntu 14.04.3 上运行。
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
#include <string>
using namespace std;
int main() {
int a, b, c, res;
string input;
char buffer [50];
b = access("/tmp/myfifo", F_OK);
if (b == -1)
a = mkfifo("/tmp/myfifo", 0777);
c = ("/tmp/myfifo", O_WRONLY);
getline(cin, input);
for (int i = 0; i < input.size(); i++)
buffer[i] = input.at(i);
res = write(c, buffer, 50);
close(c);
return 0;
}
.
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <iostream>
using namespace std;
int main() {
int c, res;
char buffer [50];
c = open("/tmp/myfifo", O_RDONLY);
res = read(c, buffer, 50);
close(c);
cout<<buffer;
return 0;
}
最佳答案
看来您在发件人的第 16 行缺少单词 open
。
c = open("/tmp/myfifo", O_WRONLY);
如果没有这个词,您的程序将调用逗号运算符,它会将 O_WRONLY
的值分配给 c
,如 here 所述.
我在运行时注意到的另一个独立错误是您没有在发送方初始化 buffer
,这意味着接收方可能会在实际字符串之后读取垃圾,因为没有空终止符。
char buffer [50];
memset(buffer, 0, 50);
关于c++ - 在两个终端之间传递缓冲区(命名管道),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33882469/