简体   繁体   中英

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. 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. (may be some thing like system("./calc/calc "); in that example) I am new in this field. 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.

I assume your pipe is configured well from parent to child.

Then child can read from other end.

dup2(fd, 1); //1 is for stdout

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.

Child can see it.

here is an example http://www.csl.mtu.edu/cs4411.ck/www/NOTES/process/shm/example-1.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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