在两个端子之间传递缓冲区(命名管道)

Passing buffer between two terminals (Named Pipe)

本文关键字:缓冲区 管道 两个 之间      更新时间:2023-10-16

我为这个错误的标题道歉,因为我不知道该怎么写。我必须用C++为一个赋值制作一个命名管道。我知道命名管道是如何工作的,以及每一行应该做什么,但我遇到了一个问题,我和一个代码相同的朋友无法解决这个问题。

这是一项简单的任务。我所要做的就是让一个程序创建命名管道,并将用户输入的char数组放入其中。第二个程序(在自己的终端中)只需从管道中读取char数组并将其输出到终端中。

在下面第二个程序的第11行(c=open("/tmp/myffo",O_RDONLY);),程序似乎从来没有运行过那一行。当我在终端中运行它时,什么也没发生,它只是坐在那里,好像处于死锁状态。我的朋友没有这个问题,我们不知道是什么原因造成的。我在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);

如果没有这个词,您的程序将调用逗号运算符,该运算符将为c分配O_WRONLY的值,如下所述。

我在运行此程序时注意到的另一个独立错误是,您没有在发送方初始化buffer,这意味着接收方可能会在实际字符串之后读取垃圾,因为没有null终止符。

char buffer [50];
memset(buffer, 0, 50);