C++捕获分叉的子对象



我有以下代码片段:

stringstream userOut;
streambuf* old = cout.rdbuf(userOut.rdbuf());
pid_t pid;
if (!(pid = fork())) {
cout << "hello from child!" << endl;
exit(0);

} else {
int status;
// wait for child to finish
wait(&status);
// give cout old buffer back
cout.rdbuf(old);
// prints nothing!
cout << "child content: " << userOut.str() << endl;
}

我希望能够捕获并重定向来自子进程的cout,以便在父进程中使用,但到目前为止,重定向的输出总是空的。造成这种情况的原因是什么?有什么可用的解决方案吗?

如注释中所述,分叉进程将获得流的副本。因此它写入输出流的副本。

通常,你想用管道来解决这种问题。如果你查阅man 2 pipe,你会在最后找到这个例子:

下面的程序创建一个管道,然后用fork(2(s创建一个子过程;子级继承了一组重复的文件描述符指的是同一管道。叉子(2(之后,每个过程都会关闭管道不需要的文件描述符(请参见管道(7((。然后,父级写入程序命令中包含的字符串-行参数,子项在来自管道的时间,并在标准输出上进行回声。

#include <sys/types.h>
#include <sys/wait.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int
main(int argc, char *argv[])
{
int pipefd[2];
pid_t cpid;
char buf;
if (argc != 2) {
fprintf(stderr, "Usage: %s <string>n", argv[0]);
exit(EXIT_FAILURE);
}
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
cpid = fork();
if (cpid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (cpid == 0) {    /* Child reads from pipe */
close(pipefd[1]);          /* Close unused write end */
while (read(pipefd[0], &buf, 1) > 0)
write(STDOUT_FILENO, &buf, 1);
write(STDOUT_FILENO, "n", 1);
close(pipefd[0]);
_exit(EXIT_SUCCESS);
} else {            /* Parent writes argv[1] to pipe */
close(pipefd[0]);          /* Close unused read end */
write(pipefd[1], argv[1], strlen(argv[1]));
close(pipefd[1]);          /* Reader will see EOF */
wait(NULL);                /* Wait for child */
exit(EXIT_SUCCESS);
}
}

最新更新