Search code examples
c++linuxpipedup2

What end of stream dup2 change?


What end of the stream does dub2 ( ) change is it the end the OS is connected to or the end connected to application .

int main(){
    FILE* file = fopen("test.txt", "w");    // Create file dexcriptor
    int num = fileno(file);       // Convert FILE* to file descriptor
    dup2(num, STDOUT_FILENO);      // Make STDOUT_FILENO an alias to num
    cout << "happy year";
    close(num);
}

this code redirect output to file and not the screen which means that input side of stream is connected now to the file right .


Solution

  • Before the dup2(), the file descriptor table for the process looks something like this:

    0 => terminal (stdin)
    1 => terminal (stdout)
    2 => terminal (stderr)
    ...
    num => file "test.txt"
    

    After the dup2(), it looks like this:

    0 => terminal (stdin)
    1 => file "test.txt"
    2 => terminal (stderr)
    ...
    num => file "test.txt"
    

    There's actually an extra level of indirection. There's a file table in the kernel for all open streams, and there's just one entry for the shared opening of test.txt. Both descriptors point to that file table entry -- this is what allows them to share the file position.

    In the C++ I/O subsystem, cout is connected to STDOUT_FILENO, so redirecting the descriptor changes where writing to cout writes.