-1
我从一个子进程重定向输出:重定向子进程输出
int pipefd[2];
pipe(pipefd);
pid_t pid = fork(); /* Create a child process */
switch (pid) {
case -1: /* Error */
cout << "Uh-Oh! fork() failed.\n";
exit(1);
case 0: /* Child process */
close(pipefd[0]);
dup2(pipefd[1], 1);
dup2(pipefd[1], 2);
close(pipefd[1]);
execv(args[0], (char * const *)args);
cout << "execv() error" << endl;
exit(1);
default: /* Parent process */
close(pipefd[1]);
char buffer[1024];
size_t bytes_read = 0;
bytes_read = read(pipefd[0], buffer, sizeof(buffer));
if(bytes_read == -1) {
cout << "read() error" << endl;
exit(1);
}
close(pipefd[0]);
if(bytes_read > 0) {
buffer[bytes_read-1] = '\0'; // Overwrite the newline
}
int status, exit_pid;
while(true) {
exit_pid = waitpid(pid, &status, 0);
if(exit_pid == -1) {
cout << "waitpid() error: " << strerror(errno) << endl;
exit(1);
}
else {
return WEXITSTATUS(status);
}
}
}
这工作得很好,当我跑它作为一个独立的代码。但是,当我将它集成到多线程环境时,会发生一件可怕的事情:read()调用以某种方式读取父进程的其他线程的输出,就好像它是子进程管道的输出一样。 任何人都遇到过这样的事情? 我在OS X.
其他线程使用stdout和stderr来写输出吗?那么这种行为绝对是正常的和可以预料的。 –
是的,但我不明白为什么这会导致这种行为。 pipe()调用分配新的文件描述符,并且子节点中的dup2()不影响父节点描述符表。 – Yuval
你知道什么['dup2(pipefd [1],1);'](http://man7.org/linux/man-pages/man2/dup.2.html),你知道吗? –