fd-safer.c 1.7 KB

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