Providing/passing argument to signal handler

后端 未结 7 1173
夕颜
夕颜 2020-12-02 10:29

Can I provide/pass any arguments to signal handler?

/* Signal handling */
struct sigaction act;
act.sa_handler = signal_handler;
/* some more settings */
         


        
7条回答
  •  渐次进展
    2020-12-02 10:58

    You can use a signal handler which is a method of a class. Then that handler can access member data from that class. I'm not entirely sure what Python does under the covers here around the C signal() call, but it must be re-scoping data?

    I was amazed that this works, but it does. Run this and then kill the process from another terminal.

    import os, signal, time
    
    class someclass:
        def __init__(self):
            self.myvalue = "something initialized not globally defined"
            signal.signal(signal.SIGTERM, self.myHandler)
        def myHandler(self, s, f):
            # WTF u can do this?
            print "HEY I CAUGHT IT, AND CHECK THIS OUT", self.myvalue
    
    
    print "Making an object"
    a = someclass()
    
    while 1:
        print "sleeping.  Kill me now."
        time.sleep(60)
    

提交回复
热议问题