首先,我打开一个文件,然后使用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;
}
你试过了吗?它有用吗?当然,它的工作原理是 – 2012-01-05 09:07:13
。 – sinners 2012-01-05 09:09:15