cloexec.c 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. /* closexec.c - set or clear the close-on-exec descriptor flag
  2. Copyright (C) 1991, 2004, 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. The code is taken from glibc/manual/llio.texi */
  14. #include <config.h>
  15. #include "cloexec.h"
  16. #include <unistd.h>
  17. #include <fcntl.h>
  18. #ifndef FD_CLOEXEC
  19. # define FD_CLOEXEC 1
  20. #endif
  21. /* Set the `FD_CLOEXEC' flag of DESC if VALUE is true,
  22. or clear the flag if VALUE is false.
  23. Return 0 on success, or -1 on error with `errno' set. */
  24. int
  25. set_cloexec_flag (int desc, bool value)
  26. {
  27. #if defined F_GETFD && defined F_SETFD
  28. int flags = fcntl (desc, F_GETFD, 0);
  29. if (0 <= flags)
  30. {
  31. int newflags = (value ? flags | FD_CLOEXEC : flags & ~FD_CLOEXEC);
  32. if (flags == newflags
  33. || fcntl (desc, F_SETFD, newflags) != -1)
  34. return 0;
  35. }
  36. return -1;
  37. #else
  38. return 0;
  39. #endif
  40. }