nonblock.c 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * Set and clear the O_NONBLOCK fcntl option on an open file.
  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. * Returns the previous state of O_NONBLOCK.
  12. */
  13. #include <stdio.h>
  14. #include <string.h>
  15. #include <stdlib.h>
  16. #include <errno.h>
  17. #include <fcntl.h>
  18. #include "putty.h"
  19. bool nonblock(int fd)
  20. {
  21. int fdflags;
  22. fdflags = fcntl(fd, F_GETFL);
  23. if (fdflags < 0) {
  24. fprintf(stderr, "%d: fcntl(F_GETFL): %s\n", fd, strerror(errno));
  25. exit(1);
  26. }
  27. if (fcntl(fd, F_SETFL, fdflags | O_NONBLOCK) < 0) {
  28. fprintf(stderr, "%d: fcntl(F_SETFL): %s\n", fd, strerror(errno));
  29. exit(1);
  30. }
  31. return fdflags & O_NONBLOCK;
  32. }
  33. bool no_nonblock(int fd)
  34. {
  35. int fdflags;
  36. fdflags = fcntl(fd, F_GETFL);
  37. if (fdflags < 0) {
  38. fprintf(stderr, "%d: fcntl(F_GETFL): %s\n", fd, strerror(errno));
  39. exit(1);
  40. }
  41. if (fcntl(fd, F_SETFL, fdflags & ~O_NONBLOCK) < 0) {
  42. fprintf(stderr, "%d: fcntl(F_SETFL): %s\n", fd, strerror(errno));
  43. exit(1);
  44. }
  45. return fdflags & O_NONBLOCK;
  46. }