파이프 및 포크 작업 방법을 배우기 위해 샘플 프로그램을 준비 중입니다. 내 기본 구현에서, 내 자식 프로세스에서, 나는 0을 닫고 파일 기술자 0이 이제 내 파이프의 읽기 끝이되도록 파이프의 읽기 끝을 복제했다.C++ 파이프 및 포크
내 부모 프로세스에서 문자열을 쓰고 자식 프로세스에서 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를뿐만 아니라 : 당신이 cin
에서 그런 식으로 읽을 때
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