Unix环境高级编程第三章习题2(转载修改)

int dup2(fd1,fd2) (int fd1,int fd2){
    int fd=0;
    int array_fd[100];
    int i=0;

    printf(" dup2(%d,%d) \n", fd1, fd2);
    if((fd1 < 0) || (fd2 < 0) || fd2 > 100){
        err_sys(" Please check file_id. ");
        exit(1);
    }
    fd = dup(fd1);
    if(fd < 0){
        err_sys(" the file id has no corresponding file ");
        exit(1);
    }
    while(fd < fd2){
        i++;
        if(i == 100){
            err_sys(" open to much file ");
            exit(1);
        }
        array_fd[i]=fd;
        fd = dup(fd1);
        if (fd < 0) {
            err_sys(" can't open it ");
        }
        printf("fd = %d \n", fd);
    }
    if(fd > fd2){
close(fd);
        close(fd2);
        fd = dup(fd1);
 }
 for(;i>=0;i--){
        close(array_fd[i]);
  }
    return fd;
}


你可能感兴趣的:(Unix环境高级编程第三章习题2(转载修改))