从 C++ 通过 RPC 启动新线程会导致进程成为僵尸?

Starting new thread via an RPC from C++ causes process to be zombied?

所以我尝试使用以下代码从 C++ 程序的 RPC 调用启动一个新线程到 Flask 服务器中的一个线程

@api.route("/open_api_connection")
def open_api_connection():

    # spawn server
    from threading import Thread
    thread = Thread(target = start_message_server)
    thread.start()

    return jsonify({"host":"localhost", "port":8080})

def start_message_server():
    while True:
        time.sleep(1)
        print "in server"

但是,当我通过 C++ 程序向该服务器发送 HTTP 请求时,Flask 服务器无法用 CTRL-c 杀死。我猜新线程不知何故变成了僵尸。 ps 显示即使在 CTRL-c 之后进程仍然是 运行。 CTRL-z 也不起作用...我正在使用内置服务器启动 Flask 服务器

api = Flask(__name__)
# import stuff ...

if __name__ == "__main__":

    # check if the port number that is used to run this script has been
    # provided or not
    if len(sys.argv) == 2:
        port = sys.argv[1]
    else:
        sys.stderr.write("Usage: python " + sys.argv[0] + " <port_number>\n")
        sys.exit(1)

    api.run(port = int(sys.argv[1]), threaded = True)

我像这样通过 C++ 中的调用连接到此服务器

open_connection("localhost", "8000");

知道为什么会发生这种情况以及如何解决这个问题吗?

我使用 signal 包解决了这个问题并使用了 os._exit(0)

import os

signal.signal(signal.SIGINT, lambda data,frame : os._exit(0))

请记住 os._exit(n) 以状态 n 退出,不调用清理处理程序、刷新 stdio 缓冲区等

查看文档 here:

A thread can be flagged as a “daemon thread”. The significance of this flag is that the entire Python program exits when only daemon threads are left. The initial value is inherited from the creating thread. The flag can be set through the daemon property.

A python 进程只会在所有非守护线程都退出时才会退出。主线程是处理标准 ctrl-c 事件(通常是 unix 信号 SIGINT)的线程,并在收到该事件时退出。任何其他非守护线程将 (a) 需要意识到主线程已退出然后自行退出,或者 (b) 是在所有其他线程退出时自动退出的守护线程。

创建线程时,尝试改为:

thread = Thread(target=start_message_server)
thread.daemon = True
thread.start()

以这种方式创建时,线程不应阻止进程关闭,如果它是唯一的事情 运行。