簡體   English   中英

C ++管道和叉子

[英]C++ pipe and 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;
}

這也是我的痕跡:

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被欺騙之前獲取緩沖數據。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM