【发布时间】:2016-02-26 05:36:40
【问题描述】:
对于这个糟糕的标题,我深表歉意,因为我不知道该如何措辞。我必须在 C++ 中为分配创建一个命名管道。我了解命名管道的工作原理以及每一行应该做什么,但我遇到了一个我和一个代码相同的朋友无法解决的问题。
这是一个简单的任务。我所要做的就是让一个程序创建命名管道并将用户输入的字符数组放入其中。第二个程序(在它自己的终端中)只是从管道中读取 char 数组并在终端中输出。
在下面的第二个程序第 11 行 (c = open("/tmp/myfifo", O_RDONLY);) 中,该程序似乎从未运行该行。当我在终端中运行它时,什么也没有发生,它只是坐在那里,好像它处于死锁状态。我的朋友没有这个问题,我们不知道是什么原因造成的。我正在使用默认终端在 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;
}
【问题讨论】:
标签: c++ linux named-pipes