stdopen.c 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. /* stdopen.c - ensure that the three standard file descriptors are in use
  2. Copyright 2005, 2007, 2013-2014 Free Software Foundation, Inc.
  3. This program is free software; you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation; either version 3, or (at your option)
  6. any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  13. /* Written by Paul Eggert and Jim Meyering. */
  14. #ifdef HAVE_CONFIG_H
  15. # include <config.h>
  16. #endif
  17. #include "stdopen.h"
  18. #include <sys/types.h>
  19. #include <sys/stat.h>
  20. #include <fcntl.h>
  21. #include <unistd.h>
  22. #include <errno.h>
  23. /* Try to ensure that all of the standard file numbers (0, 1, 2)
  24. are in use. Without this, each application would have to guard
  25. every call to open, dup, fopen, etc. with tests to ensure they
  26. don't use one of the special file numbers when opening a file.
  27. Return false if at least one of the file descriptors is initially
  28. closed and an attempt to reopen it fails. Otherwise, return true. */
  29. bool
  30. stdopen (void)
  31. {
  32. int fd;
  33. bool ok = true;
  34. for (fd = 0; fd <= 2; fd++)
  35. {
  36. if (fcntl (fd, F_GETFD) < 0)
  37. {
  38. if (errno != EBADF)
  39. ok = false;
  40. else
  41. {
  42. static const int contrary_mode[]
  43. = { O_WRONLY, O_RDONLY, O_RDONLY };
  44. int mode = contrary_mode[fd];
  45. int new_fd;
  46. /* Open /dev/null with the contrary mode so that the typical
  47. read (stdin) or write (stdout, stderr) operation will fail.
  48. With descriptor 0, we can do even better on systems that
  49. have /dev/full, by opening that write-only instead of
  50. /dev/null. The only drawback is that a write-provoked
  51. failure comes with a misleading errno value, ENOSPC. */
  52. if (mode == O_RDONLY
  53. || (new_fd = open ("/dev/full", mode) != fd))
  54. new_fd = open ("/dev/null", mode);
  55. if (new_fd != fd)
  56. {
  57. if (0 <= new_fd)
  58. close (new_fd);
  59. ok = false;
  60. }
  61. }
  62. }
  63. }
  64. return ok;
  65. }