我正在研究示例程序,以了解管道和分叉如何工作。在我的非常基本的实现,在我的子进程,我关闭0和重复管道的读端,使文件描述符0现在是我管的读取结束。C++管道和叉子
从我的父进程中,我写出了一个字符串,并在我的子进程中,我读取字符串使用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 +++
使用std :: cin.getline(BUF,的sizeof(BUF));而不是std :: cin >> buf;可以得到你想要的结果。 – lordofire