APUE习题[实现dup2函数功能,不使用fcntl]
2012-03-28 22:40
549 查看
学习,记录。
int dup2(int oldhandle, int newhandle);
函数功能:
复制文件句柄,newhandle指定的dup2和dup的区别就是可以用newfd参数指定新描述符的数值,如果newfd已经打开,则先将其关闭。如果newfd等于oldfd,则dup2返回newfd, 而不关闭它。dup2函数返回的新文件描述符同样与参数oldfd共享同一文件表项。
关键部分实现思路:
先close关闭需要复制到的文件描述符newdup。
连续dup,每dup一次产生的新的fd记录下来。
当新产生的fd等于需要产生的fd的时候,跳出循环,并把前面产生的fd全都close掉,返回该描述符。
注释挺详细,看注释吧
执行结果:
本文出自 “About:Blank H4cking” 博客,请务必保留此出处http://pnig0s1992.blog.51cto.com/393390/819830
int dup2(int oldhandle, int newhandle);
函数功能:
复制文件句柄,newhandle指定的dup2和dup的区别就是可以用newfd参数指定新描述符的数值,如果newfd已经打开,则先将其关闭。如果newfd等于oldfd,则dup2返回newfd, 而不关闭它。dup2函数返回的新文件描述符同样与参数oldfd共享同一文件表项。
关键部分实现思路:
先close关闭需要复制到的文件描述符newdup。
连续dup,每dup一次产生的新的fd记录下来。
当新产生的fd等于需要产生的fd的时候,跳出循环,并把前面产生的fd全都close掉,返回该描述符。
注释挺详细,看注释吧
执行结果:
//Code by Pnig0s1992 //Date:2012,3,28 #include <unistd.h> #include <fcntl.h> #include <string.h> #include <sys/types.h> #include <sys/stat.h> int my_dup(int olddup,int newdup); int main(int argc,char ** argv) { int newdup = 3; const char * filename = "newfile.txt"; int fd = open(filename,O_RDWR); int newfd = my_dup(fd,newdup); if(write(newfd,"Test new fd.",strlen("Test new fd.")) < 0) { printf("Use new fd write file failed."); exit(2); }else { printf("Write successfully."); } exit(0); } int my_dup(int olddup,int newdup) { int tempdup; int icount = 0; int filedesarr[newdup]; if((tempdup = dup(olddup)) == -1) //判断原文件描述服是否有效 { printf("the file desp is invalid."); exit(1); }else { close(tempdup); } if(newdup == olddup) //若新旧文件描述符相等则直接返回 { return olddup; } close(newdup);//关闭要复制的文件描述符 for(icount = 0;icount<newdup+1;icount++) //循环复制文件描述符 { filedesarr[icount] = 0; tempdup = dup(newdup); if(tempdup < 0) { return -1; }else { if(tempdup == newdup) { //若复制后的文件描述符于指定的相等则跳出 break; }else{ filedesarr[icount] = 1; //否则将对应下标的数组元素置为1 } } } for(icount = 0;icount<newdup+1;icount++) //关闭之前打开的非指定描述符 { if(filedesarr[icount] == 1) { close(icount); } } return tempdup; }
本文出自 “About:Blank H4cking” 博客,请务必保留此出处http://pnig0s1992.blog.51cto.com/393390/819830
相关文章推荐
- APUE习题[实现dup2函数功能,不使用fcntl]
- 习题3.2:不调用fcntl函数来实现dup2的功能
- APUE(习题3.2)实现与dup2功能相同的函数
- APUE习题3.2----自己实现的dup2( )函数的源码
- 不调用fcntl,自己实现dup2函数功能
- UNIX环境高级编程学习笔记(四)不调用fcntl函数实现dup2的功能
- APUE 习题3-2 实现dup2,要求不使用fcntl函数。
- APUE习题3.2----自己实现的dup2( )函数的源码
- apue第三章习题3.2 编写dup2功能相同的函数,要求不调用fcntl函数
- UNIX环境高级编程习题3.2 自己实现dup2函数功能
- [APUE]不用fcntl实现dup2函数功能
- APUE习题3.2用dup实现dup2以及shell中重定向符号的使用
- 使用lua实现php的print_r()函数功能
- 使用python实现strcmp函数功能示例
- 实现dup2功能相同的函数
- 习题 8.4 有n个整数,使前面各数顺序向后移m个位置,最后m个数变成最前面m个数,见图8.43。写一函数实现以上功能,在主函数中输入n个整数和输出调整后的n个数。
- python使用函数默认值来实现函数静态变量的功能
- 【Unity快速实现小功能】NGUI篇——快速使用UIEventListener组件实现,按钮点击功能并添加相应的处理函数
- hive中使用自定义函数(UDF)实现分析函数row_number的功能
- C语言中strtok使用方法与原理,以及自实现函数功能