2012-01-05 41 views
1

首先,我打开一个文件,然后使用dup2复制文件描述符。为什么当第一个文件描述符关闭时,我还能通过另一个文件读取文件吗?dup2不仅仅是复制文件描述符吗?

#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; 
} 
+0

你试过了吗?它有用吗?当然,它的工作原理是 – 2012-01-05 09:07:13

+0

。 – sinners 2012-01-05 09:09:15

回答

2

在猜测,实际的“打开文件描述”数据是引用计数,让所有当你复制一个文件描述符出现这种情况是因为它引用数据的计数递增。当您致电close()时,计数递减。

因此,您关闭第一个描述符实际上并不会导致第二个描述符无效。

+0

谢谢。你是对的。我发现它[关闭文件描述符](http://unix.stackexchange.com/questions/25498/what-happens-when-i-close-a-file-descriptor)。 – sinners 2012-01-05 10:21:42