LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 1161|回复: 1

如何解答APUE2里的3.2练习题?

[复制链接]
发表于 2010-1-27 22:24:20 | 显示全部楼层 |阅读模式
Write your own dup2 function that performs the same service as the dup2 function described in Section 3.12, without calling the fcntl function. Be sure to handle errors correctly.
我想用open("/dev/fd/n",mode);但不知道如何指定描述符像dup2一样?
发表于 2010-1-30 08:24:50 | 显示全部楼层
/dev/fd/n有些系统只有0,1,2,3,如果fd超过3就没有办法用这个方法了。dup递归实现

#include <unistd.h>
#include <errno.h>

int mydup2(int oldfd, int newfd)
{
        int fd;

        if (oldfd < 0 || newfd < 0
#ifdef OPEN_MAX
                        || newfd >= OPEN_MAX
#endif
                        )
        {
                errno = EBADF;
                return -1;
        }

        if (oldfd == newfd)
                return newfd;

        if ((fd = dup(oldfd)) == -1)
        {
                errno = EBADF;
                return -1;
        }

        if (fd == newfd)
                return 0;

        if (fd > newfd)
        {
                close(fd);
                close(newfd);
                fd = dup(oldfd);
                return fd;
        }

        newfd = mydup2(oldfd, newfd);
        close(fd);
        return newfd;
}
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表