[英]How to fork a child process and redirect all of the program's output to the child process?
我正在编写一个插入另一个程序的printf()
它分叉一个子进程,然后将程序的所有输出重定向到该子进程。 下面的代码是我编写的尚未运行的代码,我想我需要在其上添加此功能。
int printf(char* format, ... )
{
int res;
static void *(*mallocp)(size_t size);
char *error;
if (!mallocp) {
mallocp = dlsym(RTLD_NEXT, "printf");
if ((error = dlerror()) != NULL) {
fputs(error, stderr);
exit(1);
}
}
va_list args;
va_start(args, format);
res=mallocp(format, args);
va_end(args);
return res;
}
我找到了一种类似的解决方案,但略有不同。 在c中的子进程中重定向stdin和stdout我真的不知道在分叉一个子进程并配置好管道之后,如何让父进程继续使用系统“ printf” mallocp
给出应该重定向到子进程的stdout处理。 (在该示例中,可能类似于system("./calc/calc ");
在该领域中,我是新手。 你可以告诉我吗 ?
顺便说一句,我不知道我是否想念整个过程的实现,因为这是一个问题,我也不知道官方的解决方案。
使用“ dup2”并将“ stdout”替换为“ pipe”写文件描述符。
我认为您的管道从父级到子级的配置都很好。
然后孩子可以从另一端阅读。
dup2(fd,1); // 1用于标准输出
第二种选择:(如果您的管道不再好)
使用共享内存。
创建共享内存对象。
将STDOUT从父级重定向到共享内存。
孩子可以看到它。
这是一个示例http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/example-1.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.