cloexec.c 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. /*
  2. * Set and clear the FD_CLOEXEC fcntl option on a file descriptor.
  3. *
  4. * We don't realistically expect these operations to fail (the most
  5. * plausible error condition is EBADF, but we always believe ourselves
  6. * to be passing a valid fd so even that's an assertion-fail sort of
  7. * response), so we don't make any effort to return sensible error
  8. * codes to the caller - we just log to standard error and die
  9. * unceremoniously.
  10. */
  11. #include <stdio.h>
  12. #include <string.h>
  13. #include <stdlib.h>
  14. #include <errno.h>
  15. #include <fcntl.h>
  16. #include "putty.h"
  17. void cloexec(int fd)
  18. {
  19. int fdflags;
  20. fdflags = fcntl(fd, F_GETFD);
  21. if (fdflags < 0) {
  22. fprintf(stderr, "%d: fcntl(F_GETFD): %s\n", fd, strerror(errno));
  23. exit(1);
  24. }
  25. if (fcntl(fd, F_SETFD, fdflags | FD_CLOEXEC) < 0) {
  26. fprintf(stderr, "%d: fcntl(F_SETFD): %s\n", fd, strerror(errno));
  27. exit(1);
  28. }
  29. }
  30. void noncloexec(int fd)
  31. {
  32. int fdflags;
  33. fdflags = fcntl(fd, F_GETFD);
  34. if (fdflags < 0) {
  35. fprintf(stderr, "%d: fcntl(F_GETFD): %s\n", fd, strerror(errno));
  36. exit(1);
  37. }
  38. if (fcntl(fd, F_SETFD, fdflags & ~FD_CLOEXEC) < 0) {
  39. fprintf(stderr, "%d: fcntl(F_SETFD): %s\n", fd, strerror(errno));
  40. exit(1);
  41. }
  42. }