【问题标题】:twisted python daemonization and port bindings扭曲的 python 守护进程和端口绑定
【发布时间】:2013-10-03 00:50:08
【问题描述】:

我正在使用 Twisted 教程中的以下脚本(稍作修改):

from twisted.application import internet, service
from twisted.internet import reactor, protocol, defer
from twisted.protocols import basic
from twisted.web import client

class FingerProtocol(basic.LineReceiver):

    def lineReceived(self, user):
        d = self.factory.getUser(user)

        def onError(err):
            return "Internal server error"
        d.addErrback(onError)

        def writeResponse(message):
            self.transport.write(message + "\r\n")
            self.transport.loseConnection()
        d.addCallback(writeResponse)

class FingerFactory(protocol.ServerFactory):
    protocol = FingerProtocol

    def __init__(self, prefix):
        self.prefix = prefix

    def getUser(self, user):
        return client.getPage(self.prefix + user)

application = service.Application('finger', uid=1, gid=1)
factory = FingerFactory(prefix="http://livejournal.com/~")
internet.TCPServer(7979, factory).setServiceParent(
    service.IServiceCollection(application))

我保存为 finger_daemon.tac 并运行

twistd -y finger_daemon.tac \ 
    -l /home/me/twisted/finger.log \
    --pidfile=/home/me/twisted/finger.pid

当然它不会绑定到 79,因为它是一个特权端口。我也尝试使用 sudo 运行,没有区别。

然后我尝试将TCPServer 端口更改为 7979,然后在运行时连接到守护进程

telnet 127.0.0.1 7979

我得到Connection Refused 错误。这里具体是怎么回事?守护进程应该如何在 Twisted 中工作?

【问题讨论】:

    标签: python twisted daemon twistd


    【解决方案1】:

    当我运行此代码时,我看到以下日志消息:

    2013-10-02 23:50:34-0700 [-] failed to set uid/gid 1/1 (are you root?) -- exiting.
    

    然后twistd 退出。所以你需要做sudo twistd 然后这会增加一大堆python路径管理问题......

    为什么要设置 uidgid 参数?您想以daemon 用户身份运行它吗?你不需要为了守护进程而这样做。只需将 uid=1, gid=1 参数删除到 Application 就可以了。

    【讨论】:

    • 同样重要的是 - 您是如何看到错误的? twistd 为我默默运行
    • 我在 Twisted 上工作,所以直接链接到提到这个例子的教程会很有用:-)。
    • 我通过运行twistd -n -y finger_daemon.tac 看到了错误。通过您的调用,您应该看到同样的错误,只是在/home/me/twisted/finger.log 中。 (尽管启动错误并不总是正确报告;知道您是否看到它会很有趣!)
    • 这里是 uid/gid = 1 指示的一个示例:twistedmatrix.com/documents/current/core/howto/tutorial/…
    猜你喜欢
    • 2011-06-04
    • 2011-05-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-27
    • 2011-07-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多