4
0

fd-safer.c 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. /* Return a safer copy of a file descriptor.
  2. Copyright (C) 2005, 2006 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 2, 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. */
  15. #include <config.h>
  16. #include "unistd-safer.h"
  17. #include <errno.h>
  18. #include <unistd.h>
  19. #ifndef STDIN_FILENO
  20. # define STDIN_FILENO 0
  21. #endif
  22. #ifndef STDERR_FILENO
  23. # define STDERR_FILENO 2
  24. #endif
  25. /* Return FD, unless FD would be a copy of standard input, output, or
  26. error; in that case, return a duplicate of FD, closing FD. On
  27. failure to duplicate, close FD, set errno, and return -1. Preserve
  28. errno if FD is negative, so that the caller can always inspect
  29. errno when the returned value is negative.
  30. This function is usefully wrapped around functions that return file
  31. descriptors, e.g., fd_safer (open ("file", O_RDONLY)). */
  32. int
  33. fd_safer (int fd)
  34. {
  35. if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
  36. {
  37. int f = dup_safer (fd);
  38. int e = errno;
  39. close (fd);
  40. errno = e;
  41. fd = f;
  42. }
  43. return fd;
  44. }