stdopen.c 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. /* stdopen.c - ensure that the three standard file descriptors are in use
  2. Copyright (C) 2005, 2007 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, write to the Free Software Foundation,
  13. Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
  14. /* Written by Paul Eggert and Jim Meyering. */
  15. #ifdef HAVE_CONFIG_H
  16. # include <config.h>
  17. #endif
  18. #include "stdopen.h"
  19. #include <sys/types.h>
  20. #include <sys/stat.h>
  21. #include <fcntl.h>
  22. #include <unistd.h>
  23. #include <errno.h>
  24. /* Try to ensure that all of the standard file numbers (0, 1, 2)
  25. are in use. Without this, each application would have to guard
  26. every call to open, dup, fopen, etc. with tests to ensure they
  27. don't use one of the special file numbers when opening a file.
  28. Return false if at least one of the file descriptors is initially
  29. closed and an attempt to reopen it fails. Otherwise, return true. */
  30. bool
  31. stdopen (void)
  32. {
  33. int fd;
  34. bool ok = true;
  35. for (fd = 0; fd <= 2; fd++)
  36. {
  37. if (fcntl (fd, F_GETFD) < 0)
  38. {
  39. if (errno != EBADF)
  40. ok = false;
  41. else
  42. {
  43. static const int contrary_mode[]
  44. = { O_WRONLY, O_RDONLY, O_RDONLY };
  45. int mode = contrary_mode[fd];
  46. int new_fd;
  47. /* Open /dev/null with the contrary mode so that the typical
  48. read (stdin) or write (stdout, stderr) operation will fail.
  49. With descriptor 0, we can do even better on systems that
  50. have /dev/full, by opening that write-only instead of
  51. /dev/null. The only drawback is that a write-provoked
  52. failure comes with a misleading errno value, ENOSPC. */
  53. if (mode == O_RDONLY
  54. || (new_fd = open ("/dev/full", mode) != fd))
  55. new_fd = open ("/dev/null", mode);
  56. if (new_fd != fd)
  57. {
  58. if (0 <= new_fd)
  59. close (new_fd);
  60. ok = false;
  61. }
  62. }
  63. }
  64. }
  65. return ok;
  66. }