My implementation for APUE2e Exercise3.2: implement my own dup2 function that performs the same service as the dup2 function. Based on a little testing, it seems to work and behave as the provided dup2 function. I used the dup function to implement mydup2 function. However, I didn’t work on the error handling part, just succeed or fail.
/*
* exercise3-2.c
*
* Created on: Sep 10, 2011
* Author: zhuhuang
*/
//Goal: implement dup2 using dup
#include <apueerr.h>
//file descriptor if OK, -1 on error.
//olddes should be an existing file descriptor, otherwise error is return: Bad file descriptor.
int mydup2(int olddes, int newdes)
{
int tempdes;
int result;
if(olddes < 0 || newdes < 0)
return -1;
//err_sys("Error: a file descriptor is a non-negative integer.");
if(olddes == newdes)
return newdes;
if((tempdes = dup(olddes)) == -1)
return -1;
//err_sys("dup error"); //return -1?
if(tempdes == newdes){
return newdes;
}else if(tempdes > newdes){
close(newdes); //newdes is already open. close it to make it be the lowest-numbered available file descriptor. used for next dup call.
result = mydup2(olddes, newdes);
close(tempdes);
}else{ //tempdes < newdes. newdes is still available. keep duping until newdes is reached.
result = mydup2(olddes, newdes);
close(tempdes);
}
return result;
}
int main(void)
{
int resultdes1;
int resultdes2;
if((resultdes1 = dup(1)) == -1)
err_sys("dup error 1");
printf("File descriptor returned by dup(1): %dn", resultdes1);
/*
if((resultdes2 = dup2(1, resultdes1 + 10)) == -1)
err_sys("dup2 error 1");
printf("File descriptor returned by dup2(1, resultdes1 + 1): %dn", resultdes2);
*/
/*
//what will happen if dup a non-existing file descriptor
if((resultdes1 = dup(resultdes1 + 5)) == -1)
err_sys("dup error 2");
printf("File descriptor returned by dup(resultdes1 + 5): %dn", resultdes1);
*/
/*
//what will happen if dup a non-existing file descriptor
if((resultdes2 = dup2(resultdes1 + 5, resultdes1 + 6)) == -1)
err_sys("dup2 error 2");
printf("File descriptor returned by dup2(resultdes1 + 5, resultdes1 + 6): %dn", resultdes2);
*/
if((resultdes2 = mydup2(1, resultdes1 + 10)) == -1)
err_sys("mydup2 error 1");
printf("File descriptor returned by mydup2(1, resultdes1 + 1): %dn", resultdes2);
//what will happen if dup a non-existing file descriptor
if((resultdes2 = mydup2(resultdes1 + 5, resultdes1 + 6)) == -1)
err_sys("mydup2 error 2");
printf("File descriptor returned by dup2(resultdes1 + 5, resultdes1 + 6): %dn", resultdes2);
}