为什么在 ARM MacOS 上使用 python3 os.fork() 时父进程会执行两次?

问题描述 投票:0回答:1

我正在尝试运行 Flask 服务器和同时向其发出请求的客户端。

当我运行以下代码时:

def main():
    """
    Start a local server and call it
    using parallel processes. 
    """

    pid = os.fork()

    if pid == 0:
        # GET data
        get()
        return 0

    else:
        # Run the server
        run()
        return 0

if __name__ == "__main__":
    main()

使用cmd:

python main.py <SOME_ARGS>

我得到以下输出:

 * Serving Flask app 'server.server'         < ---- Server Starts running
 * Debug mode: on
Traceback (most recent call last):           < ---- Client runs, Error Traceback
.
.
.
requests.exceptions.ConnectionError: HTTPConnectionPool(host='127.0.0.1', port=3000): Max retries exceeded with url: / (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x100919640>: Failed to establish a new connection: [Errno 61] Connection refused'))

 * Running on http://127.0.0.1:3000.         < ---- Server finishes running

   Hello, World!                             < ---- Client runs again, this time successfully 

问题是我希望父进程运行一次,但它似乎运行了两次。

python multithreading flask fork pid
1个回答
0
投票

使用线程:您可以使用线程来并行运行 Flask 服务器和客户端,而不是 fork。

import threading
from flask import Flask
import requests
import time

app = Flask(__name__)

@app.route('/')
def hello():
    return "Hello, World!"

def run():
    app.run(port=3000)

def get():
    time.sleep(1)
    response = requests.get('http://127.0.0.1:3000')
    print(response.text)

def main():
    server_thread = threading.Thread(target=run)
    server_thread.start()
    
    get()

if __name__ == "__main__":
    main()
最新问题
© www.soinside.com 2019 - 2024. All rights reserved.