fd-safer.c 1.6 KB

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