chttp-redirectdup2redirectstandardoutputdup

Redirect standard output to file and re-establish the standard output with function


I have to create a function that temporarily redirects the standard output to a file name "file", then executes the function f, then re-establishes the original standard output.

I'm having some trouble realizing it since I am clearly not good at shell and C. I know I have to use dup() and dup2() but I have no idea how to use them.


void redirect_to (void (*f)(void), char *file)
{
 int fd = open(file, O_CREAT | O_TRUNC | O_WRONLY, 0644);
 int old = dup(file);
 dup2(fd, old);
 f();
 close(fd);
}

I am pretty sure I am doing all wrong tho but can't understand how to do it. Thank you very much..


Solution

  • I finally got the correct answer, so here is how to temporarily redirects the standard output to a file name "file", then executes the function f, then re-establishes the original standard output:

    
    void redirect_stdout (void (*f)(void), char *file)
    {
     int fd = open(file, O_CREAT | O_TRUNC | O_WRONLY, 0644);
     int savefd = dup(1);
     dup2(fd, 1);
     f();
     dup2(savefd, 1);
     close(fd);
     close(savefd);
    }