C++ 管道和 fork

标签 c++ linux pipe fork dup

我正在编写示例程序以了解管道和 fork 的工作原理。在我最基本的实现中,在我的子进程中,我关闭了 0 并复制了管道的读取端,这样文件描述符 0 现在就是我的管道的读取端。

在我的父进程中,我写出一个字符串,在我的子进程中,我使用 cin 读取字符串,因为 cin 本质上是我的管道读取端,我观察到完整的字符串没有打印出来,我似乎无法理解为什么!

#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#define TEST_STRING "Hello, Pipe!"
int main(int argc, char const *argv[]) {
  int fd[2];
  pipe(fd);

  pid_t pid;
  if ((pid = fork()) == 0) {
    //Child
    close(0);
    close(fd[1]);
    int myCin = dup(fd[0]);
    char buf[sizeof(TEST_STRING)];

    // int x;
    // std::cin >> x;
    // std::cout << x << std::endl;
    // read(myCin, buf, sizeof(TEST_STRING));
    std::cin >> buf;

    std::cout << buf << std::endl;

  }
  else {
    //parent
    write(fd[1], TEST_STRING, sizeof(TEST_STRING));
    close(fd[1]);
    waitpid(pid, NULL, 0);
  }
  return 0;
}

这也是我的 strace:

clone(child_stack=0, flags=CLONE_CHILD_CLEARTID|CLONE_CHILD_SETTID|SIGCHLD, child_tidptr=0x7fd895adaa10) = 1904
strace: Process 1904 attached
[pid  1903] write(4, "Hello, Pipe!\0", 13) = 13
[pid  1903] close(4)                    = 0
[pid  1903] wait4(1904,  <unfinished ...>
[pid  1904] close(0)                    = 0
[pid  1904] close(4)                    = 0
[pid  1904] dup(3)                      = 0
[pid  1904] fstat(0, {st_mode=S_IFIFO|0600, st_size=0, ...}) = 0
[pid  1904] read(0, "Hello, Pipe!\0", 4096) = 13
[pid  1904] fstat(1, {st_mode=S_IFCHR|0620, st_rdev=makedev(136, 2), ...}) = 0
[pid  1904] write(1, "Hello,\n", 7)     = 7
[pid  1904] read(0, "", 4096)           = 0
[pid  1904] exit_group(0)               = ?
[pid  1904] +++ exited with 0 +++

最佳答案

当您以这种方式从 cin 读取时,它将丢弃前导空格,然后在下一个空格字符处停止。所以这就是为什么它只返回它所做的。尝试 std:getline

你不应该指望 dup() 为你选择 FD 0。使用 dup2() 以便您可以指定要使用的描述符。

我也怀疑从 cin 下更改 FD 是否安全。您可以获得 FD 被欺骗之前的缓冲数据。

关于C++ 管道和 fork ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42311299/

相关文章:

c++ - 数组与 vector ,内存布局

linux - 如何为非用户更新打开文件 ulimit

c - 在linux中的同一个套接字上接收来自不同组的多播数据

angularjs - yo angular-fullstack 在本地 linux 上安装失败

c++ - IO重定向: cout not working in main

c++ - 如何从 std::shared_ptr 转换为 std::unique_ptr?

LeetCode #377的C++ DP解法,这段代码有bug吗?

c++ - std::chrono::high_resolution_clock 和屏幕刷新率的准确度(不是精度)

c++ - 多次 fork 后无法向父进程发送消息

shell - 命令来验证管道中的输入然后将其传递?