APUE 習題3-2 實現dup2,要求不使用fcntl函數。,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); } }} 測試:#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); } }} 可以把輸出重新導向到testdup2.dat,成功