自学时,编写的一个测试程序。如果有什么问题,请指出。
#include "apue.h" #include <sys/resource.h> #include <unistd.h> #include <fcntl.h> int mydup2(int fd,int fd2) { int fdt; // if fd equal fd2 ,then return fd2 if (fd == fd2) { return fd2; } // if fd2 exits ,then close it first if ( dup(fd2) != -1 ) { close(fd2); } struct rlimit limit; if (getrlimit(RLIMIT_NOFILE,&limit) == -1) { return -1; } else { printf("%d\n", (int)limit.rlim_cur); } fdt = dup(fd); for (int i = 0; i < (int)limit.rlim_cur-1-3; ++i) { if (fdt != fd2) { fdt = dup(fd); } else { break; } } for (int i = 0; i < (int)limit.rlim_cur-1-3; ++i) { if (i != fd2) { close(i+3); } } } int main() { int fd ; if (fd = open("file.hole",FILE_MODE) < 0) { err_sys("open error"); } int fd2 = 32; int fdd = mydup2(fd,fd2); if (fdd == -1) { err_sys("mydup2 error"); } else { printf("%d\n", fd2); } exit(0); }