我是 Twisted 的新手。我最近遇到了这个问题,希望得到一些帮助。据我了解,扭曲反应器作为单线程循环运行。当我生成另一个进程以从循环中获取输入时(稍后会将结果传递回循环),即使没有输入传递给它,该进程也会立即退出(参见下面的代码)。
此外,是否可以让一个衍生的进程长时间运行,而不是每次收到输入时都生成一个新进程?
感谢您的时间,
问
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()