c++ - 在两个终端之间传递缓冲区(命名管道)

标签 c++ linux named-pipes

我为糟糕的标题道歉,因为我不确定如何措辞。我必须在 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/

相关文章:

c++ - 字符常量和函数名的 sizeof() 背后的逻辑

c++ - 错误 : ISO C++ forbids in-class initialization of non-const static member

c - 在C程序中查找目录

c - Wireshark 中的帧 1 太长(-16711680 字节)错误

c++ - 如何从 C++ 中加载和调用 VBScript 函数?

c++ - 使用 SFINAE 检测成员函数

linux - 我怎样才能在一个系统上找到一个 Unix 程序的所有版本?

linux - 我如何找到系统调用(一些数字)例程的位置?

sockets - Win32 套接字与命名管道

ffmpeg - 命名管道,它们可以流式传输数据吗?