APP
系统平台
  • 建站知识
  • 联系我们
  • 咨询热线 :
    028-86922220

    域鸣明网站建设,新征程启航

    为企业提供网站建设、域名注册、服务器等服务

    实现的dup2()函数的源码怎么写

    这篇文章将为大家详细讲解有关实现的dup2( )函数的源码怎么写,文章内容质量较高,因此小编分享给大家做个参考,希望大家阅读完这篇文章后对相关知识有一定的了解。

    成都创新互联公司作为成都网站建设公司,专注网站建设公司、网站设计,有关企业网站设计方案、改版、费用等问题,行业涉及成都白乌鱼等多个领域,已为上千家企业服务,得到了客户的尊重与认可。

    原 dup2()函数:

    #include 
    
    int dup2( int fd, int fd2 );

    对于 dup2,可以用 fd2 参数指定新描述符的值。如果 fd2 已经打开,则先将其关闭。如若 fd 等于 fd2,则 dup2 返回 fd2,而不关闭它。否则,fd2 的 FD_CLOEXEC 文件描述符标志就被清除,这样 fd2 在进程调用 exec 时是打开状态。该函数返回的新文件描述符与参数 fd 共享同一个文件表项。

    下面是自己实现的 dup2函数:

    #include 
    #include 
    #include 
    #include 
    #include  
    #include 
    #include 
    #include 
    
    //检查文件描述符是否有效
    int isFileDescriptor( int fd )
    {
        struct stat st;
        if( (-1 == fstat(fd,&st)) && (EBADF == errno) )
            return -1;
        return 0;
    }
    
    int my_dup2( int oldfd, int newfd )
    {
        int tempfd;
        int fd_count;
        int fdarray[newfd];
        int res;
    
        if( -1 == isFileDescriptor( oldfd ) ) {
            printf("the file descriptor is invalid.\n");
            return -1;
        }
    
        //如果newfd等于oldfd,则直接返回newfd,而不关闭它
        if( oldfd == newfd ) 
            return newfd;
        
        //否则,关闭newfd
        if( 0 == isFileDescriptor( newfd ) ) {
            res = close( newfd );  
            if( -1 == res ) {
                perror("close file descriptor failed");
                return -1;
            }
        }
    
        //复制文件描述符
        for( fd_count=0; fd_count

    程序运行结果:

    [zhang@localhost APUE]$ ./my_dup2
    write to testfd 5 successfully
    read from initial fd 3 is: Hey man!

    测试通过。

    关于实现的dup2( )函数的源码怎么写就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。


    网站标题:实现的dup2()函数的源码怎么写
    分享路径:http://yimabatong.com/article/pcside.html
    在线咨询
    服务热线
    服务热线:028-86922220
    TOP