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 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132
| #include <stdio.h> #include <unistd.h> #include <sys/resource.h> #include <sys/errno.h>
int dup2_(int oldfd, int newfd) { int ret; int stack[7168]; int count = 0; struct rlimit old_rlim={0}; getrlimit(RLIMIT_NOFILE, &old_rlim); if (newfd < 0 || newfd > old_rlim.rlim_cur - 1) { errno = EBADF; return -1; } while(1) { ret = dup(oldfd); if(ret == -1 && errno != EMFILE) { break; } else if(ret == -1 && errno == EMFILE) { if(oldfd == newfd) { return newfd; } printf("close(newfd)\n"); close(newfd); } else { if(oldfd == newfd) { close(ret); return newfd; } if(ret == newfd) { break; } else if(ret < newfd) { stack[count++] = ret; } else { close(ret); printf("close(newfd)\n"); close(newfd); } } } while(count) { close(stack[--count]); } return ret; }
int main() { int r, max_fd; struct rlimit old_rlim={0}; getrlimit(RLIMIT_NOFILE, &old_rlim); printf("NOFILE limits: soft=%lld; hard=%lld\n", (long long) old_rlim.rlim_cur, (long long) old_rlim.rlim_max);
r = dup2_(7168, 7168); if(r == -1) { perror("dup2_(7168, 7168) fail: "); } else { printf("dup2_(7168, 7168) success return %d\n", r); }
r = dup2_(100, 100); if(r == -1) { perror("dup2_(100, 100) fail: "); } else { printf("dup2_(100, 100) success return %d\n", r); }
r = dup2_(1, 7168); if(r == -1) { perror("dup2_(1, 7168) fail: "); } else { printf("dup2_(1, 7168) success return %d\n", r); }
r = dup2_(1, 7167); if(r == -1) { perror("dup2_(1, 7167) fail: "); } else { printf("dup2_(1, 7167) success return %d\n", r); }
r = dup2_(2, 2); if(r == -1) { perror("dup2_(2, 2) fail: "); } else { printf("dup2_(2, 2) success return %d\n", r); } while((r = dup(0))!= -1) { max_fd = r; } perror(NULL); printf("max fd is %d\n", max_fd);
r = dup2_(1, 7168); if(r == -1) { perror("dup2_(1, 7168) fail: "); } else { printf("dup2_(1, 7168) success return %d\n", r); }
r = dup2_(1, 7167); if(r == -1) { perror("dup2_(1, 7167) fail: "); } else { printf("dup2_(1, 7167) success return %d\n", r); }
r = dup2_(2, 2); if(r == -1) { perror("dup2_(2, 2) fail: "); } else { printf("dup2_(2, 2) success return %d\n", r); }
return 0; }
|