关于dup2的困惑

时间:2016-03-14 19:41:31

标签: c file dup

如果我有两个文件描述符,f1和f2,我将它们打开到同一个文件:file.txt。根据我的理解,他们将指向不同的文件偏移(除非我调用dup2)。如果每个文件描述符中有不同的内容我会调用dup2会发生什么?

示例,如果我要做这样的事情:f1和f2都是file.txt的文件描述符

1)将12345写入f1

2)将678写入f2

3)调用dup2(f1,f2)

4)将9写入f2

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

2 个答案:

答案 0 :(得分:1)

只是为了理解我尝试过此代码段的问题:

#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”。

答案 1 :(得分:0)

/ dup2()使“新文件描述符”成为“旧文件描述符”的副本 / you can check the entire file descriptor here

这是一个小程序...正如你所说的文件处理点在同一个位置......我会以“追加”模式打开文件。



    #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