1

首先,我打开一个文件,然后我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;
}
4

1 回答 1

2

猜测一下,实际的“打开文件描述”数据是引用计数的,所以当你复制一个文件描述符时发生的所有事情就是它引用的数据的计数增加了。当您调用close()时,计数会减少。

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

于 2012-01-05T09:15:03.450 回答