title: time limit for unresponsive method call
body: <p>I have a Python module that's a bit buggy. Sometimes, the function calls will take forever or even segfault. It will be a long while before upstrean gets to fix this. I need to find a way to run the method <code>ball()</code> with a time limit. Unfortunately, the suggestions from <a href="https://stackoverflow.com/q/366682/353337">here</a> won't help since the process is unresponsive. Any hints?</p>
  <pre class="lang-py prettyprint-override"><code>from contextlib import contextmanager
  import signal
  import math
  import time
  from meshpy.geometry import (
      EXT_OPEN,
      GeometryBuilder,
      generate_surface_of_revolution,
  )
  from meshpy.tet import MeshInfo, build
  
  
  # function that takes about 1min
  def ball(h):
      r = 3.0
      polar_subdivision = int(math.pi / h)
      dphi = math.pi / polar_subdivision
  
      def truncate(val):
          return 0 if abs(val) &lt; 1e-10 else val
  
      rz = [
          [truncate(r * math.sin(i * dphi)), r * math.cos(i * dphi)]
          for i in range(polar_subdivision + 1)
      ]
  
      geob = GeometryBuilder()
      radial_subdivision = int(2 * math.pi / h)
      geob.add_geometry(
          *generate_surface_of_revolution(
              rz, closure=EXT_OPEN, radial_subdiv=radial_subdivision
          )
      )
  
      mesh_info = MeshInfo()
      geob.set(mesh_info)
  
      build(mesh_info)
      # time.sleep(20)  # works
  
  
  # from &lt;https://stackoverflow.com/a/601168/353337&gt;
  class TimeoutException(Exception):
      pass
  
  
  @contextmanager
  def time_limiter(seconds):
      def signal_handler(signum, frame):
          raise TimeoutException(&quot;Timed out!&quot;)
      signal.signal(signal.SIGALRM, signal_handler)
      signal.alarm(seconds)
      try:
          yield
      finally:
          signal.alarm(0)
  
  
  with time_limiter(3):
      ball(0.02)
  </code></pre>