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

来源:互联网 发布:tracker软件怎么使用 编辑:程序博客网 时间:2024/05/16 13:55
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;
}


原创粉丝点击