fcntl函数用法——复制文件描述符
文件描述符复制和输出重定向
dup() 用最小的文件描述符来复制,从0开始搜素。复制文件描述符后,最小文件描述符指向被复制描述符指向的文件。
dup2(int oldfd,int newfd) 强制用newfd来复制oldfd close(1);dup(fd) == 》等价于dup2(fd,1)
int fcntl(int fd, int cmd, ... //arg ); 功能:操纵文件描述符,改变已打开文件属性。
fcntl(fd,F_DUPFD,fd_start) :cmd=F_DUPFD,从fd_start开始搜索一个可用的文件描述符。而dup从0开始搜索。
1 #include<unistd.h> 2 #include<sys/types.h> 3 #include<sys/stat.h> 4 #include<fcntl.h> 5 #include<stdlib.h> 6 #include<stdio.h> 7 #include<errno.h> 8 #include<string.h> 9 #define ERR_EXIT(m)\ 10 do\ 11 {\ 12 perror(m);\ 13 exit(EXIT_FAILURE);\ 14 }while(0) //宏要求一条语句 15 int main(int argc,char*argv[]) 16 { 17 18 int fd; 19 fd=open("test2.txt",O_WRONLY); 20 if(fd==-1) 21 ERR_EXIT("open error"); 22 23 //复制文件描述符实现IO重定向。dup(fd),得到新的文件描述符跟前一个fd指向同一个文件,引用计数变为2 24 //close(1); 25 //dup(fd);//1被关闭,所以复制后返回的文件描述符为1.此时1指向test.txt.新文件描述符一定是当前最小的 26 //dup2(fd,1);//关掉1,1指向fd. 27 close(1); 28 if(fcntl(fd,F_DUPFD,0)<0) 29 ERR_EXIT("dup error");//从0开始搜索,1指向test2.txt 30 printf("hello\n");//不再输出到屏幕,而是到test2.txt. 总是输出到1所指向的设备。 31 return 0; 32 }