fd-safer.c 1.5 KB

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