gpt4 book ai didi

C++ 捕获 fork 子 cout

转载 作者:塔克拉玛干 更新时间:2023-11-03 02:14:18 25 4
gpt4 key购买 nike

我有以下代码片段:

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 以在父进程中使用,但到目前为止,重定向的输出始终为空。是什么导致了这种情况,是否有任何可用的解决方案?

最佳答案

如评论中所述, fork 进程获取流的拷贝。所以它写入输出流的拷贝。

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

The following program creates a pipe, and then fork(2)s to create a child process; the child inherits a duplicate set of file descriptors that refer to the same pipe. After the fork(2), each process closes the file descriptors that it doesn't need for the pipe (see pipe(7)). The parent then writes the string contained in the program's command- line argument to the pipe, and the child reads this string a byte at a time from the pipe and echoes it on standard output.

   #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);
}
}

关于C++ 捕获 fork 子 cout,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53540544/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com