2

我是 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()
4

1 回答 1

2

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

import os
print "in child", os.getpid()

打印出自己的 PID 后将立即退出。无论您是使用 Twisted 还是其他方式启动它,这都是它的行为。如果您希望它等待输入,那么您必须将代码添加到程序中。

于 2012-06-06T19:09:26.010 回答