简体   繁体   English

如何派生一个子进程并将程序的所有输出重定向到该子进程?

[英]How to fork a child process and redirect all of the program's output to the child process?

I am writing one task which interposition one other program's printf() .It forks one child process and and redirect all of the program's output to the child process. 我正在编写一个插入另一个程序的printf()它分叉一个子进程,然后将程序的所有输出重定向到该子进程。 The code below is what I have written which haven't run yet and I need to add this function on it, I guess. 下面的代码是我编写的尚未运行的代码,我想我需要在其上添加此功能。

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

I find one similar solution but a little different. 我找到了一种类似的解决方案,但略有不同。 Redirect stdin and stdout in child in c I don't really know after I fork one child process and configure pipe well, how can I let parents process go on with the system "printf" mallocp to give the stdout which should be redirected to child process. 在c中的子进程中重定向stdin和stdout我真的不知道在分叉一个子进程并配置好管道之后,如何让父进程继续使用系统“ printf” mallocp给出应该重定向到子进程的stdout处理。 (may be some thing like system("./calc/calc "); in that example) I am new in this field. (在该示例中,可能类似于system("./calc/calc ");在该领域中,我是新手。 Could you tell me ? 你可以告诉我吗 ?

BTW, I don't know if I miss understand the implement of the whole process because It is one question and I don't know the official solution. 顺便说一句,我不知道我是否想念整个过程的实现,因为这是一个问题,我也不知道官方的解决方案。

Use "dup2" and replace the "stdout" with "pipe" write file descriptor. 使用“ dup2”并将“ stdout”替换为“ pipe”写文件描述符。

I assume your pipe is configured well from parent to child. 我认为您的管道从父级到子级的配置都很好。

Then child can read from other end. 然后孩子可以从另一端阅读。

dup2(fd, 1); dup2(fd,1); //1 is for stdout // 1用于标准输出

Second option:(in case your pipe is not good any more) 第二种选择:(如果您的管道不再好)

Use shared memory. 使用共享内存。

Create shared memory object. 创建共享内存对象。

Redirect STDOUT from parent to shared memory. 将STDOUT从父级重定向到共享内存。

Child can see it. 孩子可以看到它。

here is an example http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/example-1.html 这是一个示例http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/example-1.html

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM