dup2 上的混乱

Confusion on dup2

如果我有两个文件描述符 f1f2,并且我将它们打开到同一个文件:file.txt,会发生什么情况?据我了解,它们将指向不同的文件偏移量(除非我调用 dup2)。如果每个文件描述符中有不同的东西并且我调用 dup2 会发生什么?

例如,如果我要这样做:f1f2 都是 file.txt 的文件描述符。两个文件描述符都使用标志 O_WRONLY|O_CREAT 打开,f1f2 之前打开(以防万一)。

  1. 将 12345 写入 f1

  2. 将678写入f2

  3. 致电dup2(f1, f2)

  4. 将 9 写入 f2

file.txt 现在会有什么?我的猜测只是一个包含 123459 的文件。

/dup2() 使 "the new file descriptor" 成为 "old file descriptor"/ 的副本 you can check the entire file descriptor here

这是一个小程序...如您所说,两个文件句柄都指向同一位置...我将以 "append" 模式打开文件。



    #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);
    }


输出是 123456789

为了理解这个问题,我尝试了这个片段:

#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);
}

代码片段给出了这个结果:

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

该文件似乎首先包含“12345”,然后覆盖并包含“67845”,最后附加“9”。