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;
    }
    

      

            

  • 相关阅读:
    POJ -- 3468
    HDOJ--1698
    简单的API应用
    Linux引导流程
    Python 实现网络爬虫小程序
    codeforce
    Count the string -- HDOJ 3336
    初次运行 Git 前的配置
    leetcode244- Shortest Word Distance II- medium
    leetcode243- Shortest Word Distance- easy
  • 原文地址:https://www.cnblogs.com/NeilHappy/p/2798003.html
Copyright © 2011-2022 走看看