cloexec.c 1.5 KB

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