APUE book Exercise 3.2 (no solution)

Write your own dup2 function that performs the same service as the dup2 function described in Section 3.12, without calling the fcntl function. Be sure to handle errors correctly.


Here is my solution. It doesn't handle EINTR (interrupted by a signal) since I don't know yet how to do it.
Comments, corrections and fresh solutions are appreciated.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <unistd.h>

int mydup_rec(int od,int nd){
  int fd=dup(od);
  if(fd==nd)
    return nd;
  else{
    int fd0=mydup_rec(od,nd);
    close(fd);
    return fd0;
  }
}

int mydup2(int oldd,int newd){
  int fd,fd0,maxd=sysconf(_SC_OPEN_MAX);

  if(oldd<0 || oldd>=maxd || /* check the range of descriptors */
     newd<0 || newd>=maxd || /* and if oldd is open*/
     (lseek(oldd,0,SEEK_CUR)==-1 && errno==EBADF)){
    errno=EBADF;
    return -1;
  }

  if(oldd==newd) /* if they are the same don't do anything */
    return oldd;

  close(newd);   /* close newd if open */

  return mydup_rec(oldd,newd);
}
Last edited on
Describe the dup2 functionality so that we can know what functionality you're aiming for.
Topic archived. No new replies allowed.