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
相关文章推荐
- APUE课后习题10.6练习代码
- C++primer plus第六版课后编程练习答案3.2
- 伟大的《红楼梦》课后练习答案
- 算法第八章课后练习 8.10
- c++ primer 课后练习 9.28
- 虚拟机管理课后练习
- 《IOS编程》控制逻辑课后练习 学习手记
- 课后练习
- 课后练习1.
- C++ Primer 课后练习10.16,10.17,10.18,10.19
- 第一章课后练习:第二大题(问答题)
- 做《算法》课后练习前需要做的事
- 20150910 课后练习 RPM YUM
- React-Native -课后练习
- Microsoft SQL Server 2008技术内幕:T-SQL语言基础 第二章课后练习答案
- C++ Primer Plus 第六版 所有章节课后编程练习答案
- 课后练习,银行利息c语言
- 算法设计与分析课后习题3.2
- Stack的实现和课后练习
- objective-c第四章课后练习答案