如何解决多处理 - 一揽子进程终止
我正在构建一个 GUI 来控制 Python 中的机器人。 GUI 有几个按钮,每个按钮执行一个无限循环的功能。 它就像一个房间,“干净的厨房”功能让它持续清洁,直到被打断。
为了保持 GUI 的交互性,我使用多处理在单独的进程中执行该函数。
我有一个停止函数,我调用该函数将机器人返回到家,并杀死子进程(否则子进程将到达下一行,当机器人离开厨房并离开时,它会开始转身家)。 stop 函数在主/父进程中运行,因为它不循环。
我有一个调用停止的 GUI 按钮,每当我开始一个新进程时我也会调用它。
我的进程是这样启动的:
from file1 import kitchen
from file2 import bedroom
if event == "Clean kitchen":
stoptour()
p = multiprocessing.Process(target=kitchen,args=(s,),daemon=True)
p.start()
if event == "Clean bedroom":
stoptour()
p = multiprocessing.Process(target=bedroom,daemon=True)
p.start()
传递的参数只是脚本用来连接机器人的套接字。 我的停止功能是:
def stoptour():
p.terminate()
p.kill()
s.send(bytes.fromhex(XXXX)) #command to send the stop signal to the robot
p.join()
这一切都运行没有错误,机器人停止,但随后又启动(因为子进程仍在运行)。我通过添加停止功能确认了这一点:
if p.is_alive:
print('Error,still not dead')
else:
print('Success,its dead')
每次打印“错误,仍然没有死”...
为什么 p.kill 和 p.terminate 不起作用?有什么东西会产生更多的子进程吗?
有没有办法编写我的 stoptour()
函数,使其完全不加选择地杀死所有子进程?
import socket
import PySimpleGUI as sg
import multiprocessing
import time
from file1 import room1
from file2 import room2
from file3 import room3
#Define the GUI window
layout = [[sg.Button("Room 1")],[sg.Text("Start cleaning of room1")],[sg.Button("Room 2")],[sg.Text("Start cleaning of room2")],[sg.Button("Room 3")],[sg.Text("Start cleaning room3")],[sg.Button("Stop")],[sg.Text("Stop what you're doing")]]
# Create the window
window = sg.Window("Robot Utility",layout)
#Setup TCP Connection & Connect
TCP_IP = '192.168.1.100' #IP
TCP_port = 2222 #Port
s = socket.socket(socket.AF_INET,socket.soCK_STREAM) #Setup TCP connection
s.connect((TCP_IP,TCP_port)) #Connect
#Define p so I can define stop function
if __name__ == '__main__':
p = multiprocessing.Process(target=room1,daemon=True)
p.start()
p.terminate()
p.kill()
p.join()
#Define stop function
def stoptour():
s.send(bytes.fromhex('longhexkey'))
p.terminate()
p.kill()
p.join()
s.send(bytes.fromhex('longhexkey')) #No harm stopping twice...
if p.is_alive:
print('Error,its dead')
stoptour()
#GUI event loop
while True:
event,values = window.read()
if event == "Room 1":
if __name__ == '__main__':
stoptour()
p = multiprocessing.Process(target=room1,daemon=True)
p.start()
if event == "Room 2":
if __name__ == '__main__':
stoptour()
p = multiprocessing.Process(target=room2,daemon=True)
p.start()
if event == "Room 3":
if __name__ == '__main__':
stoptour()
p = multiprocessing.Process(target=room3,daemon=True)
p.start()
if event == "Stop":
stoptour()
sg.popup("Tour stopped")
if event == sg.WIN_CLOSED:
stoptour()
s.close()
print('Closing Program')
break
window.close()
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。