#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int mydup(int i_OldFd, int i_NewFd);
int main(void)
{
int fd = -1;
fd = open("tests.c", O_RDONLY);
if(fd < 0)
{
printf("error.\n");
return -1;
}
printf("the old_fd:%d.\n", fd);
int tmp = mydup(fd, 100);
printf("the new_fd:%d.\n",tmp);
return 1;
}
int mydup(int i_OldFd, int i_NewFd)
{
if(i_OldFd < 0 || i_OldFd >256)
{
printf("Oldfd is wrong.\n");
return -1;
}
if(i_NewFd < 0 || i_NewFd > 256)
{
printf("Newfd is wrong.\n");
return -1;
}
if( i_NewFd == i_OldFd)
return i_OldFd;
int i_Arrayfd[256];
int count = 0;
close(i_NewFd);
do
{
i_Arrayfd[count] = dup(i_OldFd);
if(i_Arrayfd[count] == -1)
{
printf("dup error.\n");
break;
}
count++;
}while(i_Arrayfd[count-1] != i_NewFd);
for(int i = 0; i < count-1 ; i++)
{
close(i_Arrayfd[i]);
}
return i_Arrayfd[count-1];
}