dup 、dup2用於複製一個現存的文件描述符,當調用dup函數成功後,內核在進程中創建一個新的文件描述符,此描述符是當前可用文件描述符的最小數值。
dup2可以用nwefd參數指定新描述符的數值,如果newfd當前已經打開,則先將其關閉在做dup2操作,如果oldfd等於newfd,則dup2直接返回newfd而不用戶先關閉newfd再複製。
1 #include<stdio.h> 2 #include<stdlib.h> 3 #include<sys/types.h> 4 #include<sys/stat.h> 5 #include<fcntl.h> 6 #include<string.h> 7 int main() 8 { 9 umask(0); 10 int fd = open("./log",O_CREAT|O_WRONLY,0644); 11 if(fd<0) 12 { 13 perror("open"); 14 exit(1); 15 } 16 close(1); 17 int new_fd = dup(fd); 18 printf("the new_fd:%d\n",new_fd); 19 int count = 10; 20 char buf[1024]; 21 while(count-->0) 22 { 23 memset(buf,'\0',sizeof(buf)); 24 strcpy(buf,"hello bit"); 25 printf("%s\n",buf); 26 fflush(stdout); 27 } 28 return 0; 29 } 30 1 the new_fd:1 2 hello bit 3 hello bit 4 hello bit 5 hello bit 6 hello bit 7 hello bit 8 hello bit 9 hello bit 10 hello bit 11 hello bit 1 #include<stdio.h> 2 #include<string.h> 3 #include<stdlib.h> 4 #include<unistd.h> 5 #include<sys/types.h> 6 #include<sys/stat.h> 7 #include<fcntl.h> 8 int main() 9 { 10 umask(0); 11 int fd = open("./log",O_CREAT|O_WRONLY,0644); 12 close(1); 13 int new_fd = dup2(fd,1); 14 int done = 0; 15 char buf[1024]; 16 while(!done) 17 { 18 memset(buf,'\0',sizeof(buf)); 19 ssize_t _size = read(0,buf,sizeof(buf)-1); 20 if(_size<0) 21 { 22 perror("read"); 23 exit(1); 24 } 25 if(strncmp(buf,"quit",4)==0) 26 { 27 done = 1; 28 continue; 29 } 30 printf("%s",buf); 31 fflush(stdout); 32 } 33 return 0; 34 } [fbl@localhost dup2]$ ./my_dup2 #include<stdio.h> int main() { return 0; } quit [fbl@localhost dup2]$ vim log 1 #include<stdio.h> 2 int main() 3 { 4 return 0; 5 }