APUE習題[實現dup2函數功能,不使用fcntl]

學習,記錄。數組

int dup2(int oldhandle, int newhandle);ide

函數功能:
函數

    複製文件句柄,newhandle指定的dup2和dup的區別就是能夠用newfd參數指定新描述符的數值,若是newfd已經打開,則先將其關閉。若是newfd等於oldfd,則dup2返回newfd, 而不關閉它。dup2函數返回的新文件描述符一樣與參數oldfd共享同一文件表項。學習

關鍵部分實現思路:  
    先close關閉須要複製到的文件描述符newdup。
    連續dup,每dup一次產生的新的fd記錄下來。
    當新產生的fd等於須要產生的fd的時候,跳出循環,並把前面產生的fd全都close掉,
返回該描述符。
spa

註釋挺詳細,看註釋吧3d

執行結果:orm

  
  
  
  
  1. //Code by Pnig0s1992 
  2. //Date:2012,3,28 
  3. #include <unistd.h> 
  4. #include <fcntl.h> 
  5. #include <string.h> 
  6. #include <sys/types.h> 
  7. #include <sys/stat.h> 
  8.  
  9.  
  10. int my_dup(int olddup,int newdup); 
  11.  
  12. int main(int argc,char ** argv) 
  13.     int newdup = 3; 
  14.     const char * filename = "newfile.txt"
  15.     int fd = open(filename,O_RDWR); 
  16.     int newfd = my_dup(fd,newdup); 
  17.     if(write(newfd,"Test new fd.",strlen("Test new fd.")) < 0) 
  18.     { 
  19.         printf("Use new fd write file failed."); 
  20.         exit(2); 
  21.     }else 
  22.     { 
  23.         printf("Write successfully."); 
  24.     } 
  25.     exit(0); 
  26.  
  27. int my_dup(int olddup,int newdup) 
  28.     int tempdup; 
  29.     int icount = 0; 
  30.     int filedesarr[newdup]; 
  31.     if((tempdup = dup(olddup)) == -1) //判斷原文件描述服是否有效 
  32.     { 
  33.         printf("the file desp is invalid."); 
  34.         exit(1); 
  35.     }else 
  36.     { 
  37.         close(tempdup); 
  38.     } 
  39.  
  40.     if(newdup == olddup) //若新舊文件描述符相等則直接返回 
  41.     { 
  42.         return olddup; 
  43.     } 
  44.     close(newdup);//關閉要複製的文件描述符 
  45.     for(icount = 0;icount<newdup+1;icount++) //循環複製文件描述符 
  46.     { 
  47.         filedesarr[icount] = 0; 
  48.         tempdup = dup(newdup); 
  49.         if(tempdup < 0) 
  50.         { 
  51.             return -1; 
  52.         }else 
  53.         { 
  54.             if(tempdup == newdup) 
  55.             { //若複製後的文件描述符於指定的相等則跳出 
  56.                 break
  57.             }else
  58.                 filedesarr[icount] = 1; //不然將對應下標的數組元素置爲1 
  59.             } 
  60.         } 
  61.     } 
  62.     for(icount = 0;icount<newdup+1;icount++) //關閉以前打開的非指定描述符 
  63.     { 
  64.         if(filedesarr[icount] == 1) 
  65.         { 
  66.             close(icount); 
  67.         } 
  68.     } 
  69.     return tempdup; 
相關文章
相關標籤/搜索