gpt4 book ai didi

python - 从 Makefile 中终止进程

转载 作者:行者123 更新时间:2023-11-28 22:05:19 25 4
gpt4 key购买 nike

我正在尝试编写一个 makefile 来复制我编写的客户端/服务器程序(实际上只是两个 Python 脚本,但这不是真正关心的问题)...

test:
python server.py 7040 &
python subscriber.py localhost 7040 &
python client.py localhost 7040;

所以我运行 make test

并且我能够从 client.py 输入消息:

python server.py 7040 & 
python subscriber.py localhost 7040 &
python client.py localhost 7040;
Enter a message:

客户端输入空消息时,他关闭连接并成功退出。现在,我如何自动关闭聊天室的 subscriber(它只是一个“监听器”)——这将依次退出 server 进程。

我试图使用 pidof 从这些调用中获取进程 ID - 但不确定那是否是正确的路径。我不是 makefile 专家;也许我可以编写一个快速的 Python 脚本,从我的 makefile 中执行它来为我完成工作?任何建议都会很棒。


编辑:

我已经开始编写 Python 脚本路由,并且具有以下内容:

import server
import client
import subscriber
#import subprocess

server.main(8092)
# child = subprocess.Popen("server.py",shell=False)
subscriber.main('localhost',8090)
client.main('localhost', 8090)

但是,现在我收到错误消息,指出我的全局变量未定义(我认为这与将 main 方法添加到我的 server 直接相关(和 subscriberclient,但我还没说到那么远:)。这可能值得一个单独的问题...

这是我的服务器代码:

import socket
import select
import sys
import thread
import time

# initialize list to track all open_sockets/connected clients
open_sockets = []

# thread for each client that connects
def handle_client(this_client,sleeptime):
global message,client_count,message_lock,client_count_lock

while 1:
user_input = this_client.recv(100)

if user_input == '':
break

message_lock.acquire()
time.sleep(sleeptime)
message += user_input
message_lock.release()
message = message + '\n'

this_client.sendall(message)

# remove 'this_client' from open_sockets list
open_sockets.remove(this_client)
this_client.close()

client_count_lock.acquire()
client_count -= 1
client_count_lock.release()


def main(a):
server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

port = a
server.bind(('', port))
server.listen(5)
message = ''
message_lock = thread.allocate_lock()
client_count = 2
client_count_lock = thread.allocate_lock()

for i in range(client_count):
(client,address) = server.accept()
open_sockets.append(client)
thread.start_new_thread(handle_client,(client,2))

server.close()

while client_count > 0:
pass

print '************\nMessage log from all clients:\n%s\n************' % message

if __name__ == "__main__":
if sys.argv[1]:
main(int(sys.argv[1]))
else:
main(8070)

最佳答案

在脚本中使用普通的旧 bash,获取 PID 并使用 kill

或者,更好的是,创建一个测试脚本来处理所有这些并从您的 Makefile 中调用 that。例如,单个 run_tests.py。

您希望在 Makefile 之外保留尽可能多的逻辑。

关于python - 从 Makefile 中终止进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5544706/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com