zoukankan      html  css  js  c++  java
  • linux下dup2的实现

            这是apue的一个习题,要求不用fcntl来实现dup2.这是我的思路:循环调用dup复制file descriptor,直到与指定的相同。如果您有更高效的方法,请告诉小弟我,非常感谢!

            代码如下:

    #include <apue.h>
    #include <unistd.h>
    #include <my_error.h>
    #include <fcntl.h>
    #define MAX 1000
    
    //function:neil_dup2
    int neil_dup2(int filedes,int filedes2)
    {
        if(filedes2==filedes)
            return filedes;
        close(filedes2);
        int fd_list[MAX]={0};
        int i,j;
        for(i=0;i<=filedes2;i++)
        {
            if( (fd_list[i]=dup(filedes))<0)  
                err_sys("error dup!");
            if(fd_list[i]==filedes2)
                break;
        }
        for(j=0;j<i;j++)
            close(fd_list[j]);
        return fd_list[i];
    }
    
    
    int main()
    {
        int fd1;
        int fd2=10;
        int n=0;
        char buf[]="1234567891";
        if( (fd1=open("temp.foo",O_RDWR))<0 )
            err_sys("open error!");
        dup2(fd1,fd2);
        if( (n=write(fd2,buf,10))!=10)
            error("error write");
        close(fd1);
        close(fd2);
        return 0;
    }
    

      

            

  • 相关阅读:
    项目Alpha冲刺Day7
    项目Alpha冲刺Day5
    项目Alpha冲刺Day6
    Alpha冲刺总结
    测试随笔
    项目Alpha冲刺Day12
    高校征信系统项目Postmortem结果
    冲刺合集
    总结随笔
    测试工作安排
  • 原文地址:https://www.cnblogs.com/NeilHappy/p/2798003.html
Copyright © 2011-2022 走看看