1 | #!/usr/bin/python |
---|
2 | |
---|
3 | import os, signal, time |
---|
4 | from twisted.internet import reactor, defer |
---|
5 | |
---|
6 | def terminate(): |
---|
7 | print "terminating ..." |
---|
8 | d = defer.Deferred() |
---|
9 | # do things that lasts long (eg. database, network, etc.) |
---|
10 | reactor.callLater(1, d.callback, None) |
---|
11 | return d |
---|
12 | |
---|
13 | pid = os.getpid() |
---|
14 | if os.fork(): |
---|
15 | # parent |
---|
16 | reactor.addSystemEventTrigger('before', 'shutdown', terminate) |
---|
17 | reactor.run() |
---|
18 | else: |
---|
19 | time.sleep(0.5) |
---|
20 | os.kill(pid, signal.SIGTERM) |
---|
21 | time.sleep(0.5) |
---|
22 | os.kill(pid, signal.SIGTERM) |
---|
23 | |
---|
24 | |
---|
25 | # Output without patch: |
---|
26 | # 1. 'terminate' method is called twice |
---|
27 | """ |
---|
28 | terminating... |
---|
29 | terminating... |
---|
30 | """ |
---|
31 | |
---|
32 | # Output with patch: |
---|
33 | # 1. 'terminate' method is called once, as expected |
---|
34 | """ |
---|
35 | terminating... |
---|
36 | """ |
---|
37 | |
---|