APUE课后练习3.2

#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>

int mydup2(int filedes, int filedes2);
char * getpathname(char * abpathname, char * compathname);

int main(void)
{
        int fd;
        if ((fd = mydup2(2, 0)) < 0)
        {
                perror("mydup");
                exit(1);
        }
        printf("I have got fd = %d\n", fd);

        return 0;
}

/*获得open的路径名
@abpathname  某个目录的绝对路径
@compathname 相对于目录abpathname的相对路径*/
char * getpathname(char * abpathname, char * compathname)
{
        int pathlen;
        char * path;
        pathlen = strlen(abpathname) + strlen(compathname) + 1;
        path = (char *)malloc(sizeof(char) * pathlen);
        if (!path)
        {
                perror("malloc");
                exit(1);
        }
        sprintf(path, "%s%s", abpathname, compathname);   //拼接出完整路径名
        return path;
}

/*完成文件描述符的分配,作用同dup2*/
int mydup2(int filedes, int filedes2)
{
        int fd, startfd, endfd, mode;
        char *pathname;
        char file[10];
        int pathlen;
        if (filedes == filedes2)
                return filedes;
        sprintf(file, "%d", filedes);
        pathname = getpathname("/dev/fd/", file);
        mode = fcntl(filedes, F_GETFL, 0);
        close(filedes2);
        if ((fd = open(pathname, mode)) < 0)
        {
                perror("open");
                return -1;
        }
        for (startfd = fd, endfd = filedes2; fd < endfd;)
        {
                free(pathname);
                sprintf(file, "%d", fd);
                pathname = getpathname("/dev/fd/", file);
                if ((fd = open(pathname, mode)) < 0)
                {
                        perror("Cannot dup");
                        return -1;
                }
        }
        while (--endfd >= startfd)
                close(endfd);
                return fd;
}

运行后输出结果为:

I have got fd = 0


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值