user2770808
user2770808

Reputation: 347

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.

Upvotes: 0

Views: 254

Answers (2)

Pooja Jhadhav
Pooja Jhadhav

Reputation: 49

/dup2() makes "the new file descriptor" be the copy of "old file descriptor"/ you can check the entire file descriptor here

here is a little program...as you said both the file handle point in the same location...and i would open the file in "append" mode.



    #include"stdio.h"
    #include"unistd.h"
    #include"fcntl.h"
    main()
    {
    FILE *f1,*f2;
    f1 = fopen("file.txt","a");     //file opened in append So the file pointer would always point in the last location
    f2 = fopen("file.txt","a");
    fprintf(f1,"12345\n");
    fprintf(f2,"678\n");
    dup2(f1,1);                 //this is a function call REMEMBER THAT
    fprintf(f2,"9\n");
    fclose(f1);
    fclose(f2);
    }


the output is 123456789

Upvotes: -1

Edouard Thiel
Edouard Thiel

Reputation: 6218

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.

Upvotes: 2

Related Questions