fd-safer-flag.c 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. /* Adjust a file descriptor result so that it avoids clobbering
  2. STD{IN,OUT,ERR}_FILENO, with specific flags.
  3. Copyright (C) 2005-2006, 2009-2013 Free Software Foundation, Inc.
  4. This program is free software: you can redistribute it and/or modify
  5. it under the terms of the GNU General Public License as published by
  6. the Free Software Foundation; either version 3 of the License, or
  7. (at your option) any later version.
  8. This program is distributed in the hope that it will be useful,
  9. but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. GNU General Public License for more details.
  12. You should have received a copy of the GNU General Public License
  13. along with this program. If not, see <http://www.gnu.org/licenses/>. */
  14. /* Written by Paul Eggert and Eric Blake. */
  15. #include <config.h>
  16. /* Specification. */
  17. #include "unistd-safer.h"
  18. #include <errno.h>
  19. #include <unistd.h>
  20. /* Return FD, unless FD would be a copy of standard input, output, or
  21. error; in that case, return a duplicate of FD, closing FD. If FLAG
  22. contains O_CLOEXEC, the returned FD will have close-on-exec
  23. semantics. On failure to duplicate, close FD, set errno, and
  24. return -1. Preserve errno if FD is negative, so that the caller
  25. can always inspect errno when the returned value is negative.
  26. This function is usefully wrapped around functions that return file
  27. descriptors, e.g., fd_safer_flag (open ("file", O_RDONLY | flag), flag). */
  28. int
  29. fd_safer_flag (int fd, int flag)
  30. {
  31. if (STDIN_FILENO <= fd && fd <= STDERR_FILENO)
  32. {
  33. int f = dup_safer_flag (fd, flag);
  34. int e = errno;
  35. close (fd);
  36. errno = e;
  37. fd = f;
  38. }
  39. return fd;
  40. }