Back to index

nagios-plugins  1.4.16
getdtablesize.c
Go to the documentation of this file.
00001 /* getdtablesize() function for platforms that don't have it.
00002    Copyright (C) 2008-2010 Free Software Foundation, Inc.
00003    Written by Bruno Haible <bruno@clisp.org>, 2008.
00004 
00005    This program is free software: you can redistribute it and/or modify
00006    it under the terms of the GNU General Public License as published by
00007    the Free Software Foundation; either version 3 of the License, or
00008    (at your option) any later version.
00009 
00010    This program is distributed in the hope that it will be useful,
00011    but WITHOUT ANY WARRANTY; without even the implied warranty of
00012    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00013    GNU General Public License for more details.
00014 
00015    You should have received a copy of the GNU General Public License
00016    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
00017 
00018 #include <config.h>
00019 
00020 /* Specification.  */
00021 #include <unistd.h>
00022 
00023 #if (defined _WIN32 || defined __WIN32__) && ! defined __CYGWIN__
00024 
00025 #include <stdio.h>
00026 
00027 /* Cache for the previous getdtablesize () result.  */
00028 static int dtablesize;
00029 
00030 int
00031 getdtablesize (void)
00032 {
00033   if (dtablesize == 0)
00034     {
00035       /* We are looking for the number N such that the valid file descriptors
00036          are 0..N-1.  It can be obtained through a loop as follows:
00037            {
00038              int fd;
00039              for (fd = 3; fd < 65536; fd++)
00040                if (dup2 (0, fd) == -1)
00041                  break;
00042              return fd;
00043            }
00044          On Windows XP, the result is 2048.
00045          The drawback of this loop is that it allocates memory for a libc
00046          internal array that is never freed.
00047 
00048          The number N can also be obtained as the upper bound for
00049          _getmaxstdio ().  _getmaxstdio () returns the maximum number of open
00050          FILE objects.  The sanity check in _setmaxstdio reveals the maximum
00051          number of file descriptors.  This too allocates memory, but it is
00052          freed when we call _setmaxstdio with the original value.  */
00053       int orig_max_stdio = _getmaxstdio ();
00054       unsigned int bound;
00055       for (bound = 0x10000; _setmaxstdio (bound) < 0; bound = bound / 2)
00056         ;
00057       _setmaxstdio (orig_max_stdio);
00058       dtablesize = bound;
00059     }
00060   return dtablesize;
00061 }
00062 
00063 #endif