开发者

Twisted program and TERM signal

I have a simple example:

    from twisted.internet import utils,reactor

    def test:
        utils.getProcessOutput(executable="/bin/sleep",args=["10000"])

    reactor.callWhenRunning(test)
    reactor.run()

when I send signal "TERM" to program, "sleep" continues to be carried out, when I press Ctrl-开发者_Python百科C on keyboard "sleep" stopping. ( Ctrl-C is not equivalent signal TERM ?) Why ? How to kill "sleep" after send signal "TERM" to this program ?


Ctrl-C sends SIGINT to the entire foreground process group. That means it gets send to your Twisted program and to the sleep child process.

If you want to kill the sleep process whenever the Python process is going to exit, then you may want a before shutdown trigger:

def killSleep():
    # Do it, somehow

reactor.addSystemEventTrigger('before', 'shutdown', killSleep)

As your example code is written, killSleep is difficult to implement. getProcessOutput doesn't give you something that easily allows the child to be killed (for example, you don't know its pid). If you use reactor.spawnProcess and a custom ProcessProtocol, this problem is solved though - the ProcessProtocol will be connected to a process transport which has a signalProcess method which you can use to send a SIGTERM (or whatever you like) to the child process.

You could also ignore SIGINT and this point and then manually deliver it to the whole process group:

import os, signal

def killGroup():
    signal.signal(signal.SIGINT, signal.SIG_IGN)
    os.kill(-os.getpgid(os.getpid()), signal.SIGINT)

reactor.addSystemEventTrigger('before', 'shutdown', killGroup)

Ignore SIGINT because the Twisted process is already shutting down and another signal won't do any good (and will probably confuse it or at least lead to spurious errors being reported). Sending a signal to -os.getpgid(os.getpid()) is how to send it to your entire process group.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜