自己实现dup2

 转自  http://blog.csdn.net/todd911/article/details/11747097

#include <stdio.h>  
#include <unistd.h>  
  
int main(void){  
    int fd = -1;  
    fd = mydup2(0,10);  
    if(fd < 0){            
        perror("mydup2");  
        return -1;  
    }  
    printf("fd = %d\n",fd); 
    return 0;  
}  
  
int mydup2(int fd, int newfd){  
    //判断fd和newfd的范围是否正确  
    if(fd < 0 || fd > 256){  
        printf("fd is wrong.\n");  
        return -1;  
    }     int index = 0;  
    int fdarray[newfd];  
    //判断fd是否已经被打开。  
    if((fdarray[index] = dup(fd)) == -1){  
        printf("error while dup.\n");  
        return -1;  
    }else{  
        close(fdarray[index]);  
    }   
    //如果相等,则直接返回。  
    if(fd == newfd){  
        return fd;  
    }  
    //将newfd关闭  
    close(newfd);  
    //获取所要的newfd  
    int newfdindex;  
    for(index=0; index<=newfd; index++){  
        fdarray[index] = dup(fd);  
        if(fdarray[index] == -1){  
            printf("error while dup.\n");  
            return -1;  
        }else{  
            if(fdarray[index] == newfd){  
                newfdindex = index;  
                break;  
            }  
        }  
    }  
    //将之前打开的fd都关闭  
    for(index=0; index<newfdindex; index++){  
        close(fdarray[index]);  
    }  
    return fdarray[newfdindex];  
}  

 

 

posted @ 2015-06-24 09:21  neteasefans  阅读(363)  评论(0编辑  收藏  举报