免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
12
最近访问板块 发新帖
楼主: blueprint1981
打印 上一主题 下一主题

[函数] UNIX环境下,如何实现dup2函数,不允许调用fcntl? [复制链接]

论坛徽章:
0
11 [报告]
发表于 2007-04-27 05:59 |只看该作者
     In dup2(), the value of the new descriptor newd is specified.  If this
     descriptor is already in use, it is first deallocated as if a close(2)
     call had been done first.  When newd equals oldd, dup2() just returns
     without affecting the close-on-exec flag.

论坛徽章:
0
12 [报告]
发表于 2008-10-17 11:41 |只看该作者
提示: 作者被禁止或删除 内容自动屏蔽

论坛徽章:
0
13 [报告]
发表于 2009-02-12 16:12 |只看该作者
int my_dup2(int oldfd, int newfd)

{

int i, fd[newfd>oldfd?newfdldfd];

/* newfd is equal oldfd then we do nothing just return */

if (newfd == oldfd) return newfd;

/* close newfd whether newfd is a real fd */

close(newfd);

for (i = 0;  (fd = dup(oldfd)) != newfd; i++) ;

for (i–; i >= 0; i–) close(fd);

return newfd;

}

论坛徽章:
0
14 [报告]
发表于 2009-05-07 21:39 |只看该作者
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <error.h>
#include <sys/stat.h>
#include <sys/types.h>

int my_dup2(int oldfd, int newfd)

{

        int i, fd[newfd>oldfd?newfdldfd], fd2;

        /* newfd is equal oldfd then we do nothing just return */
       
        if (newfd == oldfd)
                return newfd;

        /* close newfd whether newfd is a real fd */

        close(newfd);

        for (i = 0;  (fd = dup(oldfd)) != newfd; i++) ;
    fd2 = fd;
        for (i--; i >= 0; i--) close(fd);

        return fd2;

}

int main(void)
{
        int fd, fd2 ,i;
        char string[] ="adfasfasDF";
        char buf[1024]={'\0'};
        struct stat statbuf;
        fd = open("tmpfile", O_CREAT|O_RDWR|O_TRUNC, S_IRUSR|S_IWUSR);       
        if(fd == -1)
        {
                perror("error";
                exit(1);
        }
       
        i = write(fd,string,sizeof(string));
        if(i == -1)
        {
                perror("werror";
                exit(1);
        }
       
        fd2 = fd +3;
       
        i= my_dup2(fd,fd2);

        lseek(fd2,-sizeof(string), 1);
        i=read(fd2, buf, sizeof(string));
        printf("buf1: %s\n", buf);
        return 0;
}

论坛徽章:
0
15 [报告]
发表于 2009-05-08 00:19 |只看该作者
呵呵, 以前回过了的,俺用的笨办法~~
http://bbs.chinaunix.net/viewthread.php?tid=1049414#pid9993690

论坛徽章:
0
16 [报告]
发表于 2009-05-08 13:01 |只看该作者
dup2是个原子操作,实现的不能适应任何环境吧

论坛徽章:
0
17 [报告]
发表于 2009-05-08 14:40 |只看该作者
原帖由 logicBaby 于 2009-5-8 00:19 发表
呵呵, 以前回过了的,俺用的笨办法~~
http://bbs.chinaunix.net/viewthread.php?tid=1049414#pid9993690


用dup来实现dup2

论坛徽章:
0
18 [报告]
发表于 2012-07-16 23:19 |只看该作者
学习了 貌似这样确实可以
那个DUP函数回来的FD是随机的呢还是递增的?能确保递增吗?
但是会有什么出错异常呢?
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP