Funktionierender Prototyp des Serious Games zur Vermittlung von Wissen zu Software-Engineering-Arbeitsmodellen.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

_signals.py 8.2KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. # -*- test-case-name: twisted.internet.test.test_sigchld -*-
  2. # Copyright (c) Twisted Matrix Laboratories.
  3. # See LICENSE for details.
  4. """
  5. This module is used to integrate child process termination into a
  6. reactor event loop. This is a challenging feature to provide because
  7. most platforms indicate process termination via SIGCHLD and do not
  8. provide a way to wait for that signal and arbitrary I/O events at the
  9. same time. The naive implementation involves installing a Python
  10. SIGCHLD handler; unfortunately this leads to other syscalls being
  11. interrupted (whenever SIGCHLD is received) and failing with EINTR
  12. (which almost no one is prepared to handle). This interruption can be
  13. disabled via siginterrupt(2) (or one of the equivalent mechanisms);
  14. however, if the SIGCHLD is delivered by the platform to a non-main
  15. thread (not a common occurrence, but difficult to prove impossible),
  16. the main thread (waiting on select() or another event notification
  17. API) may not wake up leading to an arbitrary delay before the child
  18. termination is noticed.
  19. The basic solution to all these issues involves enabling SA_RESTART
  20. (ie, disabling system call interruption) and registering a C signal
  21. handler which writes a byte to a pipe. The other end of the pipe is
  22. registered with the event loop, allowing it to wake up shortly after
  23. SIGCHLD is received. See L{twisted.internet.posixbase._SIGCHLDWaker}
  24. for the implementation of the event loop side of this solution. The
  25. use of a pipe this way is known as the U{self-pipe
  26. trick<http://cr.yp.to/docs/selfpipe.html>}.
  27. From Python version 2.6, C{signal.siginterrupt} and C{signal.set_wakeup_fd}
  28. provide the necessary C signal handler which writes to the pipe to be
  29. registered with C{SA_RESTART}.
  30. """
  31. import contextlib
  32. import errno
  33. import os
  34. import signal
  35. import socket
  36. from zope.interface import Attribute, Interface, implementer
  37. from twisted.python import failure, log, util
  38. from twisted.python.runtime import platformType
  39. if platformType == "posix":
  40. from . import fdesc, process
  41. def installHandler(fd):
  42. """
  43. Install a signal handler which will write a byte to C{fd} when
  44. I{SIGCHLD} is received.
  45. This is implemented by installing a SIGCHLD handler that does nothing,
  46. setting the I{SIGCHLD} handler as not allowed to interrupt system calls,
  47. and using L{signal.set_wakeup_fd} to do the actual writing.
  48. @param fd: The file descriptor to which to write when I{SIGCHLD} is
  49. received.
  50. @type fd: C{int}
  51. """
  52. if fd == -1:
  53. signal.signal(signal.SIGCHLD, signal.SIG_DFL)
  54. else:
  55. def noopSignalHandler(*args):
  56. pass
  57. signal.signal(signal.SIGCHLD, noopSignalHandler)
  58. signal.siginterrupt(signal.SIGCHLD, False)
  59. return signal.set_wakeup_fd(fd)
  60. def isDefaultHandler():
  61. """
  62. Determine whether the I{SIGCHLD} handler is the default or not.
  63. """
  64. return signal.getsignal(signal.SIGCHLD) == signal.SIG_DFL
  65. class _IWaker(Interface):
  66. """
  67. Interface to wake up the event loop based on the self-pipe trick.
  68. The U{I{self-pipe trick}<http://cr.yp.to/docs/selfpipe.html>}, used to wake
  69. up the main loop from another thread or a signal handler.
  70. This is why we have wakeUp together with doRead
  71. This is used by threads or signals to wake up the event loop.
  72. """
  73. disconnected = Attribute("")
  74. def wakeUp():
  75. """
  76. Called when the event should be wake up.
  77. """
  78. def doRead():
  79. """
  80. Read some data from my connection and discard it.
  81. """
  82. def connectionLost(reason: failure.Failure) -> None:
  83. """
  84. Called when connection was closed and the pipes.
  85. """
  86. @implementer(_IWaker)
  87. class _SocketWaker(log.Logger):
  88. """
  89. The I{self-pipe trick<http://cr.yp.to/docs/selfpipe.html>}, implemented
  90. using a pair of sockets rather than pipes (due to the lack of support in
  91. select() on Windows for pipes), used to wake up the main loop from
  92. another thread.
  93. """
  94. disconnected = 0
  95. def __init__(self, reactor):
  96. """Initialize."""
  97. self.reactor = reactor
  98. # Following select_trigger (from asyncore)'s example;
  99. client = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  100. client.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1)
  101. with contextlib.closing(
  102. socket.socket(socket.AF_INET, socket.SOCK_STREAM)
  103. ) as server:
  104. server.bind(("127.0.0.1", 0))
  105. server.listen(1)
  106. client.connect(server.getsockname())
  107. reader, clientaddr = server.accept()
  108. client.setblocking(0)
  109. reader.setblocking(0)
  110. self.r = reader
  111. self.w = client
  112. self.fileno = self.r.fileno
  113. def wakeUp(self):
  114. """Send a byte to my connection."""
  115. try:
  116. util.untilConcludes(self.w.send, b"x")
  117. except OSError as e:
  118. if e.args[0] != errno.WSAEWOULDBLOCK:
  119. raise
  120. def doRead(self):
  121. """
  122. Read some data from my connection.
  123. """
  124. try:
  125. self.r.recv(8192)
  126. except OSError:
  127. pass
  128. def connectionLost(self, reason):
  129. self.r.close()
  130. self.w.close()
  131. class _FDWaker(log.Logger):
  132. """
  133. The I{self-pipe trick<http://cr.yp.to/docs/selfpipe.html>}, used to wake
  134. up the main loop from another thread or a signal handler.
  135. L{_FDWaker} is a base class for waker implementations based on
  136. writing to a pipe being monitored by the reactor.
  137. @ivar o: The file descriptor for the end of the pipe which can be
  138. written to wake up a reactor monitoring this waker.
  139. @ivar i: The file descriptor which should be monitored in order to
  140. be awoken by this waker.
  141. """
  142. disconnected = 0
  143. i = None
  144. o = None
  145. def __init__(self, reactor):
  146. """Initialize."""
  147. self.reactor = reactor
  148. self.i, self.o = os.pipe()
  149. fdesc.setNonBlocking(self.i)
  150. fdesc._setCloseOnExec(self.i)
  151. fdesc.setNonBlocking(self.o)
  152. fdesc._setCloseOnExec(self.o)
  153. self.fileno = lambda: self.i
  154. def doRead(self):
  155. """
  156. Read some bytes from the pipe and discard them.
  157. """
  158. fdesc.readFromFD(self.fileno(), lambda data: None)
  159. def connectionLost(self, reason):
  160. """Close both ends of my pipe."""
  161. if not hasattr(self, "o"):
  162. return
  163. for fd in self.i, self.o:
  164. try:
  165. os.close(fd)
  166. except OSError:
  167. pass
  168. del self.i, self.o
  169. @implementer(_IWaker)
  170. class _UnixWaker(_FDWaker):
  171. """
  172. This class provides a simple interface to wake up the event loop.
  173. This is used by threads or signals to wake up the event loop.
  174. """
  175. def wakeUp(self):
  176. """Write one byte to the pipe, and flush it."""
  177. # We don't use fdesc.writeToFD since we need to distinguish
  178. # between EINTR (try again) and EAGAIN (do nothing).
  179. if self.o is not None:
  180. try:
  181. util.untilConcludes(os.write, self.o, b"x")
  182. except OSError as e:
  183. # XXX There is no unit test for raising the exception
  184. # for other errnos. See #4285.
  185. if e.errno != errno.EAGAIN:
  186. raise
  187. if platformType == "posix":
  188. _Waker = _UnixWaker
  189. else:
  190. # Primarily Windows and Jython.
  191. _Waker = _SocketWaker # type: ignore[misc,assignment]
  192. class _SIGCHLDWaker(_FDWaker):
  193. """
  194. L{_SIGCHLDWaker} can wake up a reactor whenever C{SIGCHLD} is
  195. received.
  196. """
  197. def __init__(self, reactor):
  198. _FDWaker.__init__(self, reactor)
  199. def install(self):
  200. """
  201. Install the handler necessary to make this waker active.
  202. """
  203. installHandler(self.o)
  204. def uninstall(self):
  205. """
  206. Remove the handler which makes this waker active.
  207. """
  208. installHandler(-1)
  209. def doRead(self):
  210. """
  211. Having woken up the reactor in response to receipt of
  212. C{SIGCHLD}, reap the process which exited.
  213. This is called whenever the reactor notices the waker pipe is
  214. writeable, which happens soon after any call to the C{wakeUp}
  215. method.
  216. """
  217. _FDWaker.doRead(self)
  218. process.reapAllProcesses()