您的位置:首页 > 产品设计 > UI/UE

APUE课后练习3.2

2012-11-06 16:20 225 查看
#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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: