dup2函数用于复制文件描述符(fd),它的函数原型:
int dup2(int oldfd, int newfd);
3 . 2 编写一个同3 . 1 2节中的dup2功能相同的函数,要求不调用f c n t l函数并且要有正确的
出错处理.
递归实现:
-
int mydup2(int oldfd, int newfd)
-
{
-
int tfd;
-
if(newfd <0)
-
return -1;
-
if(newfd == oldfd)
-
return newfd;
-
close(newfd);
-
if( (tfd = dup(oldfd) ) == newfd)
-
{
-
return newfd;
-
-
}else{
-
mydup2(oldfd,newfd);
-
close(tfd);
-
}
-
return newfd;
-
-
}
迭代实现:
-
int mydup2(int oldfd, int newfd)
-
{
-
if(newfd < 0)
-
return -1;
-
if(newfd == oldfd)
-
return newfd;
-
close(newfd);
-
int tfd;
-
while(1)
-
{
-
tfd = dup(oldfd);
-
if( tfd == newfd)
-
{
-
return newfd;
-
}
-
else
-
{
-
tfd = dup(oldfd);
-
close(tfd);
-
}
-
}
-
return newfd;
-
}
参考:《UNIX环境高级编程第三章文件I/O》
阅读(4540) | 评论(0) | 转发(1) |