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

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掉,返回该描述符。

注释挺详细,看注释吧

执行结果:





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