1

First, I open a file, then I use dup2 to copy the file descriptor. Why, when the first file descriptor is closed, can I still read the file through the other one?

#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>

int main(int argc, char *argv[])
{
    int fd,fd2=7;   /*7 can be any number < the max file desc*/
    char buf[101];

    if((fd = open(argv[1], O_RDONLY))<0)      /*open a file*/
        perror("open error");
    dup2(fd,fd2);                             /*copy*/
    close(fd);

    if(read(fd2,buf,100)<0)
        perror("read error");
    printf("%s\n",buf);

    return 0;
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
sinners
  • 121
  • 1
  • 4

1 Answers1

2

At a guess, the actual "open file description" data is reference-counted, so that all that happens when you duplicate a file descriptor is that the count for the data it references is incremented. When you call close(), the count is decremented.

Thus, your closing of the first descriptor doesn't actually render the second one invalid.

unwind
  • 391,730
  • 64
  • 469
  • 606
  • thank you. you are right. i find it [close-file-descriptor](http://unix.stackexchange.com/questions/25498/what-happens-when-i-close-a-file-descriptor). – sinners Jan 05 '12 at 10:21