C ++管道和叉子 [英] C++ pipe and fork

查看:75
本文介绍了C ++管道和叉子的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究一个示例程序,以了解管道和分支的工作方式.在我的基本实现中,在子进程中,我关闭了0并复制了管道的读取端,因此文件描述符0现在是管道的读取端.

I'm working on a sample program to learn how pipes and forking works. In my very basic implementation, in my child process, i closed 0 and duplicated the read end of the pipe so that file descriptor 0 is now the read end of my pipe.

在父进程中,我写了一个字符串,在子进程中,我使用cin读取了该字符串,因为cin本质上是我读取管道的末端,而我观察到的是没有打印出完整的字符串,我似乎不明白为什么!

From my parent process, I write out a string, and in my child process, I read the string using cin as cin essentially is my read end of the pipe and what I observe is the complete string does not print out and I can't seem to understand why!

#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;
}

这也是我的踪迹:

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 .

When you read from cin that way it will discard leading whitespace and then stop at the next whitespace character. So that's why it only returned what it did. Try std:getline.

您不应该依靠 dup()为您选择FD 0.使用 dup2(),以便您可以指定要使用的描述符.

You shouldn't count on dup() choosing FD 0 for you. Use dup2() so you can specify what descriptor to use.

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

I also doubt changing the FD from under cin is safe. You could get buffered data from before the FD was duped.

这篇关于C ++管道和叉子的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆