首先,我打开一个文件,然后使用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 :(得分:2)
猜测,实际的“打开文件描述”数据是引用计数的,因此复制文件描述符时发生的所有事情都是它引用的数据的计数递增。当你拨打close()
时,计数会减少。
因此,关闭第一个描述符实际上并不会使第二个描述符无效。