getdtablesize.c 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. /* getdtablesize() function for platforms that don't have it.
  2. Copyright (C) 2008-2010 Free Software Foundation, Inc.
  3. Written by Bruno Haible <bruno@clisp.org>, 2008.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. #include <config.h>
  15. /* Specification. */
  16. #include <unistd.h>
  17. #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
  18. #include <stdio.h>
  19. /* Cache for the previous getdtablesize () result. */
  20. static int dtablesize;
  21. int
  22. getdtablesize (void)
  23. {
  24. if (dtablesize == 0)
  25. {
  26. /* We are looking for the number N such that the valid file descriptors
  27. are 0..N-1. It can be obtained through a loop as follows:
  28. {
  29. int fd;
  30. for (fd = 3; fd < 65536; fd++)
  31. if (dup2 (0, fd) == -1)
  32. break;
  33. return fd;
  34. }
  35. On Windows XP, the result is 2048.
  36. The drawback of this loop is that it allocates memory for a libc
  37. internal array that is never freed.
  38. The number N can also be obtained as the upper bound for
  39. _getmaxstdio (). _getmaxstdio () returns the maximum number of open
  40. FILE objects. The sanity check in _setmaxstdio reveals the maximum
  41. number of file descriptors. This too allocates memory, but it is
  42. freed when we call _setmaxstdio with the original value. */
  43. int orig_max_stdio = _getmaxstdio ();
  44. unsigned int bound;
  45. for (bound = 0x10000; _setmaxstdio (bound) < 0; bound = bound / 2)
  46. ;
  47. _setmaxstdio (orig_max_stdio);
  48. dtablesize = bound;
  49. }
  50. return dtablesize;
  51. }
  52. #endif