首先,我打开一个文件,然后使用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;
}发布于 2012-01-05 17:15:03
根据猜测,实际的“打开文件描述”数据是引用计数的,因此当您复制文件描述符时,所有发生的事情都是它引用的数据的计数递增。当您调用close()时,计数会递减。
因此,关闭第一个描述符实际上并不会使第二个描述符无效。
https://stackoverflow.com/questions/8739926
复制相似问题