non_blocking.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. """
  2. Derived from
  3. > https://github.com/rudolfwalter/pygdbmi/blob/0.7.4.2/pygdbmi/gdbcontroller.py
  4. > MIT License https://github.com/rudolfwalter/pygdbmi/blob/master/LICENSE
  5. > Copyright (c) 2016 Chad Smith <grassfedcode <at> gmail.com>
  6. """
  7. import os
  8. if os.name == "nt": # pragma: no cover
  9. import msvcrt
  10. from ctypes import POINTER, WinError, byref, windll, wintypes # type: ignore
  11. from ctypes.wintypes import BOOL, DWORD, HANDLE # type: ignore
  12. else: # pragma: no cover
  13. import fcntl
  14. def make_non_blocking(file_obj): # pragma: no cover
  15. """
  16. make file object non-blocking
  17. Windows doesn't have the fcntl module, but someone on
  18. stack overflow supplied this code as an answer, and it works
  19. http://stackoverflow.com/a/34504971/2893090
  20. """
  21. if os.name == "nt":
  22. LPDWORD = POINTER(DWORD)
  23. PIPE_NOWAIT = wintypes.DWORD(0x00000001)
  24. SetNamedPipeHandleState = windll.kernel32.SetNamedPipeHandleState
  25. SetNamedPipeHandleState.argtypes = [HANDLE, LPDWORD, LPDWORD, LPDWORD]
  26. SetNamedPipeHandleState.restype = BOOL
  27. h = msvcrt.get_osfhandle(file_obj.fileno())
  28. res = windll.kernel32.SetNamedPipeHandleState(h, byref(PIPE_NOWAIT), None, None)
  29. if res == 0:
  30. raise ValueError(WinError())
  31. else:
  32. # Set the file status flag (F_SETFL) on the pipes to be non-blocking
  33. # so we can attempt to read from a pipe with no new data without locking
  34. # the program up
  35. fcntl.fcntl(file_obj, fcntl.F_SETFL, os.O_NONBLOCK)