Tuesday, March 19, 2013

Redirection Using dup & dup2

dup and dup2 are basic I/O Unix system calls. Following program shows a sequence of dup operations that temporarily redirect the standard out put to "stdout.log" file. If we then want to use the original standard output we can duplicate that using dup2 system call, with help of already saved file descriptor fd.


// File Name: redirect.c

 #include <stdio.h>

   void main()
    {
        // File descriptor        

         int    fd;

        // This object is used to specify a position within a file     
         fpos_t pos;

        printf("\n stdout is normal ");
        fflush(stdout);

        //Getting current position in stream
        fgetpos(stdout, &pos);

        // Redirecting standard output to stdout.log file
        fd = dup(fileno(stdout));
        freopen("stdout.log", "w", stdout);

        fun();
        fflush(stdout);

        // Standard output is restoring to original settings
        dup2(fd, fileno(stdout));
        close(fd);
        clearerr(stdout);
        fsetpos(stdout, &pos);

        printf("\n stdout is normal again\n");
    }

    fun()
    {
    printf("stdout in f() is redirected to this file(stdout.log)");
    }

To run : gcc redirect.c
              ./a.out

After running above 2 commands you can see a file named stdout.log in your current directory with content "stdout in f() is redirected to this file(stdout.log)".

No comments:

Post a Comment