dup2替换

今天看APUE上一道题,要求不能用fcnt1来替换dup1.

刚开始的思路是dup一个,测试发现与期望的不一致就马上关闭,发现遇到无限循环,刚才想了下,才发现一旦close掉,再次dup仍然是分配最小的fd,所以永远也得不到最终的结果。囧!

好吧,依据网友的,自己整理了下:

#include <stdio.h>
#include <dirent.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <error.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>


#define err_sys(info)                                                        \
        {                                                                        \
                fprintf(stderr, "%s.\n", info);                \
                exit(EXIT_FAILURE);                                                \
        }
#define MaxFD 1024

int test_dup(int fd1,int fd2){
    /* dup2(fd1,fd2) */
    int fd=0;
    int array_fd[MaxFD];
    int i=0;

    printf(" dup2(%d,%d) \n", fd1, fd2);
    if((fd1 < 0) || (fd2 < 0) || fd2 > MaxFD)
    {
        err_sys(" Please check file_id. ");
    }
    fd = dup(fd1);
    if(fd < 0)
    {
        err_sys(" the file id has no corresponding file ");
    }

    while(fd < fd2 && i++ < MaxFD)
    {
        //close(array_fd[i-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(fd2);
        fd = dup(fd1);
    }
    for(;i>=0;i--)
    {
        close(array_fd[i]);
    }

    return fd;
}
int main(int argc, char* argv[])
{
    test_dup(1,100);
    exit(0);
}

  

posted @ 2013-09-25 22:03  hailong  阅读(255)  评论(0编辑  收藏  举报