Search code examples
cfiledup2

Confusion on dup2


What happens if I have two file descriptors, f1 and f2, and I open them to the same file: file.txt. From my understanding they will be pointing to different file offsets (unless I call dup2). What would happen if there was something different in each file descriptor and I called dup2?

Example, If I were to do something like this: both f1 and f2 are file descriptors to file.txt. Both file descriptors are opened with flags O_WRONLY|O_CREAT, with f1 being opened before f2 (in case that matters).

  1. write 12345 to f1

  2. write 678 to f2

  3. call dup2(f1, f2)

  4. write 9 to f2

What would the file.txt have now? My guess is just a file with 123459 in it.


Solution

  • Just to understand the question I have tried this snippet:

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>
    #include <sys/stat.h>
    #include <fcntl.h>
    
    int main(){
      int f1 = open ("test1.txt", O_WRONLY|O_CREAT, 0644);
      int f2 = open ("test1.txt", O_WRONLY|O_CREAT, 0644);
      write (f1, "12345", 5);
      write (f2, "678", 3);
      dup2 (f1, f2);  // this closes f2
      write (f2, "9", 1);
      close (f1);
      close (f2);
    }
    

    The snippet gives this result:

    $ gcc -Wall -std=c99 test1.c -o test1
    $ ./test1
    $ cat test1.txt
    678459
    

    It seems that the file contains first "12345", then it is overwritten and contains "67845", and finally, "9" is appended.