写一个dup2功能相同的函数,不能调用 fcntl 函数,并且要有出错处理
2015-08-17 16:58
459 查看
实现的时候用到系统原来的dup函数
// mydup2.c // 2015/08/17 Lucifer Zhang version1.0 // write my own dup2 function // use dup() function when inplementation #include <unistd.h> // include dup() #include <stdio.h> #include <stdlib.h> #define OPEN_MAX 256 /* * when the descriptor is negative or greater than OPEN_MAX, will make a errro * */ int my_dup2(int fd, int newfd); int main(int argc, char *argv[]) { int newfd, return_fd; if (argc != 2) { printf("usage: a.out test.txt\n"); exit(0); } printf("Please input the descriptor than you want to set: "); scanf("%d", &newfd); // open a file int fd = open(argv[1], 0); if (fd == -1) { perror(argv[1]); // print error msg exit(0); } printf("old descriptor is: %d\n", fd); return_fd = my_dup2(fd, newfd); printf("new descriptor is: %d\n"); close(fd); close(return_fd); exit(0); } int my_dup2(int fd, int newfd) { int count = 0; int fdarry[newfd]; // record opened descriptor if (newfd < 0 || newfd > OPEN_MAX) { printf("the new descriptor error!\n"); exit(0); } // dup() return the lowest-numbered available file descriptor if ((fdarry[count] = dup(fd)) == -1) { printf("dup() function error!\n"); exit(0); } else { // test old file descriptor if can be used close(fdarry[count]); } // if fd equals newfd, then dup2 returns newfd without closing it if (fd == newfd) { return fd; } close(newfd); // close // the main implementation for (count = 0; count <= newfd; ++count) { if ((fdarry[count] = dup(fd)) == -1) { printf("dup() funciont error!\n"); exit(0); } else { printf("the descriptor is: %d\n", fdarry[count]); if (fdarry[count] == newfd) { break; } } } for (count = 0; count <= newfd; ++count) { if (fdarry[count] == newfd) { return fdarry[count]; } else { close(fdarry[count]); } } }
相关文章推荐
- MySQL命令行备份还原数据库
- 欢迎使用CSDN-markdown编辑器
- django 如何使用django自带的user做外键
- PHP调优
- 解决微信扫码下载的两个方法
- Win10系统下怎么给电脑设置双屏显示?
- C++ map的基本操作和使用
- Java常用23种设计模式详解
- hdu4933 Miaomiao's Function 数位dp+大数模板
- 面试中如何回答“你是否愿意加班”
- SAP项目MM调研清单
- 树
- 在字符串中找出连续最长的数字串
- sublime text 2中Emmet8个常用的技巧
- exchange 2013 邮件收发流程
- JSONMdel的一步到位
- php redis函数库
- Android 下拉刷新上拉加载 多种应用场景 超级大放送(上)
- hdoj 2544 最短路【三种方法】
- 替换文件中的相关单词(二)之文件类型为doc或者docx