新しいクライアントがサーバーに接続するたびに、サーバーがmultiprocessing
モジュールを使用して新しいプロセスを生成するクライアントサーバーアプリケーションを開発しています。そのターゲット関数は、ソケットを取得して I/O を実行する関数です。私が抱えている問題は、クライアントとサーバー上のプロセスの間で TCP 接続が閉じられると、子プロセスを終了するために .join() 関数呼び出しをどのように/どこに配置すればよいですか? また、C のように親プロセスで waitpid を実行する必要がありますか?
サーバーコード:
def new_client(conn_socket):
while True:
message = conn_socket.recv(BUFFER_SIZE)
conn_socket.send(message)
#just echo the message
#how to check to see if the TCP connection is still alive?
#put the .join() here??
def main():
#create the socket
server_socket = socket(AF_INET,SOCK_STREAM)
#bind the socket to the local ip address on a specific port and listen
server_port = 12000
server_socket.bind(('',server_port))
server_socket.listen(1)
#enter in a loop to accept client connections
while True:
connection_socket, client_address = server_socket.accept()
#create a new process with the new connection_socket
new_process = Process(target = new_client, args = (connection_socket,))
new_process.start()
#put the .join() here or what??
if __name__ == '__main__':
main()
thread
また、このセットアップでは、モジュールでスレッドを使用するか、プロセスにとどまる方が有益でしょうか? サーバーコードは、「平均的な」仕様のサーバーで頻繁に使用するために開発されています (このセットアップを最適化する方法)。