Portable build framework for OpenNTPD
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

62 lines
1.7 KiB

  1. /*
  2. * Copyright (c) 2004-2005, 2007, 2010, 2012-2014
  3. * Todd C. Miller <Todd.Miller@courtesan.com>
  4. *
  5. * Permission to use, copy, modify, and distribute this software for any
  6. * purpose with or without fee is hereby granted, provided that the above
  7. * copyright notice and this permission notice appear in all copies.
  8. *
  9. * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
  10. * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
  11. * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
  12. * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
  13. * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
  14. * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
  15. * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  16. */
  17. #include <sys/types.h>
  18. #include <fcntl.h>
  19. #include <limits.h>
  20. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <unistd.h>
  23. #ifndef OPEN_MAX
  24. #define OPEN_MAX 256
  25. #endif
  26. /*
  27. * Close all file descriptors greater than or equal to lowfd.
  28. * This is the expensive (fallback) method.
  29. */
  30. int
  31. closefrom(int lowfd)
  32. {
  33. long fd, maxfd;
  34. /*
  35. * Fall back on sysconf() or getdtablesize(). We avoid checking
  36. * resource limits since it is possible to open a file descriptor
  37. * and then drop the rlimit such that it is below the open fd.
  38. */
  39. #ifdef HAVE_SYSCONF
  40. maxfd = sysconf(_SC_OPEN_MAX);
  41. #else
  42. maxfd = getdtablesize();
  43. #endif /* HAVE_SYSCONF */
  44. if (maxfd < 0)
  45. maxfd = OPEN_MAX;
  46. for (fd = lowfd; fd < maxfd; fd++) {
  47. #ifdef __APPLE__
  48. /* Avoid potential libdispatch crash when we close its fds. */
  49. (void) fcntl((int) fd, F_SETFD, FD_CLOEXEC);
  50. #else
  51. (void) close((int) fd);
  52. #endif
  53. }
  54. return 0;
  55. }