如何保持Twisted spawnProcess生成的进程长时间运行?

时间:2012-06-06 17:59:23

标签: python twisted

我是Twisted的新手。我最近遇到了这个问题,希望得到一些帮助。据我所知,扭曲的反应器作为单线程循环运行。当我生成另一个进程来从循环中获取输入时(稍后会将结果传递回循环),即使没有传入任何输入,该进程也会立即退出(参见下面的代码)。 p>

此外,是否可以保持一个衍生进程长时间运行,而不是每次收到输入时生成一个新进程?

感谢您的时间,

Q

from sys import executable
from os import environ
import os
from twisted.internet import reactor
from twisted.internet.protocol import Protocol
from twisted.internet.protocol import Factory
from twisted.internet import protocol

implementation = """\
import os
print "in child", os.getpid()
"""

class Echo(Protocol):
    def dataReceived(self, data):
        reactor.spawnProcess(pp, executable, [executable, "-c", implementation], env=environ)
        self.transport.write(data)

class EchoFactory(Factory):
    def buildProtocol(self, addr):
        return Echo()

class MyPP(protocol.ProcessProtocol):

    def connectionMade(self):
        print "connectionMade!"
    def outReceived(self, data):
        print "out", data
    def errReceived(self, data):
        print "error", data
    def inConnectionLost(self):
        print "inConnectionLost! stdin is closed! (we probably did it)"
    def outConnectionLost(self):
        print "outConnectionLost! The child closed their stdout!"
    def errConnectionLost(self):
        print "errConnectionLost! The child closed their stderr."
    def processExited(self, reason):
        print "processExited, status %d" % (reason.value.exitCode,)
    def processEnded(self, reason):
        print "processEnded, status %d" % (reason.value.exitCode,)
        print "quitting"

reactor.listenTCP(8200, EchoFactory())
pp = MyPP()
print 'in parent', os.getpid()
reactor.spawnProcess(pp, executable, [executable, "-c", implementation], env=environ)
reactor.run()

1 个答案:

答案 0 :(得分:2)

Twisted不控制子进程何时退出。子进程负责该进程(有一两个例外,这里无关紧要)。您的子进程,运行此代码的Python程序:

import os
print "in child", os.getpid()
一旦打印出自己的PID,

就会退出。无论您是使用Twisted还是其他方式启动它,都会出现这种情况。如果您希望它等待输入,那么您必须为该程序添加代码。