[APUE] Exercise3.2

 

 

 

3.2

Write your own dup2 function that performs the same service as the dup2 function described in Section 3.12, without calling the fcntl function. Be sure to handle errors correctly.

 

1 #include "assert.h" 2 #include <unistd.h> 3 #include <stdio.h> 4 5 int DUP2(int oldFd, int newFd) 6 { 7 int tmpFd; 8 int resFd; 9 //error input 10 if(oldFd<0 || newFd<0) 11 { 12 printf("wrong oldFd/newFd!"); 13 return 0; 14 } 15 16 tmpFd = dup(oldFd); 17 //error dup :( 18 if(tmpFd < -1) 19 { 20 printf("dup error!"); 21 return 1; 22 } 23 24 //lucky :) 25 if(tmpFd == newFd) 26 { 27 return tmpFd; 28 } 29 30 //newFd already open 31 if(tmpFd > newFd) 32 { 33 close(newFd); 34 close(tmpFd); 35 tmpFd = dup(oldFd); 36 assert(tmpFd == newFd); 37 return tmpFd; 38 } 40 resFd = DUP2(oldFd, newFd); 41 close(tmpFd); 42 return resFd; 43 } 44 45 int main() 46 { 47 printf("%d/n", DUP2(0, 1)); 48 return 0; 49 }

 

 

你可能感兴趣的:([APUE] Exercise3.2)