如何以编程方式杀死扭曲的 websocket 服务器

How to kill a twisted websocket server programmatically

如何以编程方式终止 websocket 服务器?我将把这个服务器和其他东西一起部署到生产环境中。我喜欢构建一个单独的 python 脚本,向所有内容发送终止信号。我不知道如何在没有用户键盘中断或 kill -9 的情况下杀死这个东西。

sys.exit() 无效。

psutil 和 terminate() 也不起作用

import os
import psutil

current_system_pid = os.getpid()

ThisSystem = psutil.Process(current_system_pid)
ThisSystem.terminate()

我没主意了。现在我在命令行上用 kill -9 杀死它。

当我用各种方法杀死它时,它往往会在下面看到这条消息,但代币仍然是运行

2020-12-12 12:24:54-0500 [autobahn.twisted.websocket.WebSocketServerFactory] (TCP Port 8080 Closed)
2020-12-12 12:24:54-0500 [-] Stopping factory <autobahn.twisted.websocket.WebSocketServerFactory object at 0x110680f28>

高速公路安装:

pip install autobahn[twisted]

代码:

from autobahn.twisted.websocket import WebSocketServerProtocol, WebSocketServerFactory
import sys
from twisted.python import log
from twisted.internet import reactor

class MyServerProtocol(WebSocketServerProtocol):

    def onConnect(self, request):
        print("Client connecting: {0}".format(request.peer))

    def onOpen(self):
        print("WebSocket connection open.")

    def onMessage(self, payload, isBinary):
        print("Text message received: {0}".format(payload.decode('utf8')))

        # echo back message verbatim
        # self.sendMessage(payload, isBinary)

    def onClose(self, wasClean, code, reason):
        print("WebSocket connection closed: {0}".format(reason))


def StopWebsocketServer():
    PrintAndLog_FuncNameHeader("Begin")
    reactor.stop()
    PrintAndLog_FuncNameHeader("End")


if __name__ == '__main__':   
    # TODO remove the logging that came in the example
    log.startLogging(sys.stdout)

    factory = WebSocketServerFactory("ws://127.0.0.1:8080")
    factory.protocol = MyServerProtocol

    # note to self: if using putChild, the child must be bytes...
    reactor.listenTCP(Port_ws, factory)
    reactor.run()

解决方案 使用@Jean-Paul Calderone 的回答:

    import os
    import signal
    os.kill(os.getpid(), signal.SIGKILL)

我有一个外部 python 脚本,它向我的每个 python 脚本发送终止信号。 kill 信号只是每个脚本都知道要查找的文件的存在。一旦终止信号出现,每个脚本都知道在它被终止前还有 x 秒。这样他们就有几秒钟的时间优雅地完成一些事情。

twisted.internet.reactor.stop() 是导致反应堆关闭的方式。这通常是导致基于 Twisted 的程序退出的原因(当然,如果程序在反应器关闭后执行更多操作,则不一定非要退出 - 但这种情况并不常见)。

但是,听起来您似乎不想知道进程中 运行 的 Python 代码是什么来结束它。您想知道某些 other 进程可以对您的基于 Twisted 的进程 什么以使其退出。您给出了两个解决方案 - KeyboardInterrupt 和 SIGKILL。您没有提到为什么这两种解决方案中的任何一种都不合适。他们对我来说很好。

如果您对 SIGKILL 感到不自在(毕竟您不应该这样,您的程序可能会因多种原因过早终止,您应该准备好应对这种情况)那么您可能忽略了以下内容KeyboardInterrupt 只是默认 SIGINT 处理程序在 Python 程序内部引发的异常。

如果您将 SIGINT 发送到基于 Twisted 的进程,那么在正常使用情况下,这将停止反应器并允许有序关闭。