0

When I press Ctrl+C the call jumps into signal_handler as expected, but the greenlets are not getting killed as they continue the process.

# signal handler to process after catch ctrl+c command
def signal_handler(signum, frame):
    print("Inside Signal Handler")
    gevent.sleep(10)
    print("Signal Handler After sleep")
    gevent.joinall(maingreenlet)
    gevent.killall(maingreenlet,block=True,timeout=10)
    gevent.kill(block=True)
    sys.exit(0)

def main():
 signal.signal(signal.SIGINT, signal_handler) // Catching Ctrl+C

 try:
   maingreenlet = [] // Creating a list of greenlets
   while True:
    for key,profileval in profile.items():
      maingreenlet.append(gevent.spawn(key,profileval)) # appending all grrenlets to list
      gevent.sleep(0)
  except (Error) as e:
    log.exception(e)
    raise

if __name__ == "__main__":
    main()
i alarmed alien
  • 9,412
  • 3
  • 27
  • 40

1 Answers1

0

The main reason your code is not working is because the variable maingreenlet is defined inside the main function, and is out of the scope of the signal_handler function which tries to access it. Your code should throw an error like this:

NameError: global name 'maingreenlet' is not defined

If you were to move the line maingreenlet = [] into the global scope, i.e. anywhere outside of the two def blocks, the greenlets should get killed without problem.

Of course that's after you fix the other issues in your code, like using // instead of # to start the comments, or calling the function gevent.kill with the wrong parameter. (you didn't specify your gevent version but I assume the current version 1.3.7) Actually this function call is redundant after you call gevent.killall.

Learn to use a Python debugger liker pdb or rpdb2 to help you debug your code. It'll save your precious time in the long run.

Gao Yuan
  • 492
  • 5
  • 10