posix.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970
  1. #!/usr/bin/env python
  2. #
  3. # Copyright 2011 Facebook
  4. #
  5. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  6. # not use this file except in compliance with the License. You may obtain
  7. # a copy of the License at
  8. #
  9. # http://www.apache.org/licenses/LICENSE-2.0
  10. #
  11. # Unless required by applicable law or agreed to in writing, software
  12. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  13. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  14. # License for the specific language governing permissions and limitations
  15. # under the License.
  16. """Posix implementations of platform-specific functionality."""
  17. from __future__ import absolute_import, division, print_function, with_statement
  18. import fcntl
  19. import os
  20. from . import interface
  21. def set_close_exec(fd):
  22. flags = fcntl.fcntl(fd, fcntl.F_GETFD)
  23. fcntl.fcntl(fd, fcntl.F_SETFD, flags | fcntl.FD_CLOEXEC)
  24. def _set_nonblocking(fd):
  25. flags = fcntl.fcntl(fd, fcntl.F_GETFL)
  26. fcntl.fcntl(fd, fcntl.F_SETFL, flags | os.O_NONBLOCK)
  27. class Waker(interface.Waker):
  28. def __init__(self):
  29. r, w = os.pipe()
  30. _set_nonblocking(r)
  31. _set_nonblocking(w)
  32. set_close_exec(r)
  33. set_close_exec(w)
  34. self.reader = os.fdopen(r, "rb", 0)
  35. self.writer = os.fdopen(w, "wb", 0)
  36. def fileno(self):
  37. return self.reader.fileno()
  38. def write_fileno(self):
  39. return self.writer.fileno()
  40. def wake(self):
  41. try:
  42. self.writer.write(b"x")
  43. except IOError:
  44. pass
  45. def consume(self):
  46. try:
  47. while True:
  48. result = self.reader.read()
  49. if not result:
  50. break
  51. except IOError:
  52. pass
  53. def close(self):
  54. self.reader.close()
  55. self.writer.close()