문제

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;
}
도움이 되었습니까?

해결책

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top