APUE Exercise 3-2 implements dup2 and does not require the use of the fcntl function ., Dup2fcntl
Int mydup2 (int oldfd, int newfd) {int tfd = 0; if (newfd <0) {err_sys ("newfd <0");} if (newfd = oldfd) {return oldfd;} while (1) {tfd = dup (oldfd); if (tfd = newfd) {return newfd;} else if (tfd> newfd) {close (newfd) ;}} test: # include "apue. h "# include <fcntl. h> int mydup2 (int oldfd, int newfd); int main (void) {int fd = 0; fd = open ("testdup2.dat", O_RDWR | O_CREAT | O_TRUNC ); if (fd <0) {printf ("open error. \ n "); return-1;} if (mydup2 (fd, STDOUT_FILENO) <0) {printf (" mydup2 error \ n "); return-1 ;} printf ("slk \ n"); return 0;} int mydup2 (int oldfd, int newfd) {int tfd = 0; if (newfd <0) {err_sys ("newfd <0");} if (newfd = oldfd) {return oldfd;} while (1) {tfd = dup (oldfd ); if (tfd = newfd) {return newfd;} else if (tfd> newfd) {close (newfd) ;}} can redirect the output to testdup2.dat. Success