Question

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;
}
Was it helpful?

Solution

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top