提问人:vilizu 提问时间:10/25/2023 更新时间:10/25/2023 访问量:36
如何按特定顺序终止进程?
How to terminate processes in a specific order?
问:
我有三个任务。
1: 2: 3:get_input (P0)
clean_input (C0)
find_missing (P1)
第一个任务是第二个任务的父进程,第三个任务是它自己的进程。它们应按以下顺序终止: 在 P1 找到丢失的字母并打印结果后,P1 应终止。当 P1 终止时,C0 应删除共享内存段并终止。P0 应在 C0 终止后终止。
我不确定如何正确实现这一点,因为我不太习惯 python 或多处理。
这是我到目前为止所拥有的:
import os
import multiprocessing as mp
import multiprocessing.shared_memory
import string
import sys
# Function for Task 1 (Get_Input)
def get_input(pipe, queue):
print(f"P0 ({os.getpid()}): Task 1 (Get_Input) started.")
sys.stdin = open(0)
test_string = input("Enter the test string: ")
# Send test string to child process
pipe.send(test_string)
queue.put("Task 1 (Get_Input) completed.")
print(f"P0 ({os.getpid()}): Task 1 (Get_Input) completed.")
# Function for Task 2 (Clean_Input)
def clean_input(pipe, shm, queue):
print(f"C0 ({os.getpid()}): Task 2 (Clean_Input) started.")
# Receive test string from parent process
test_string = pipe.recv()
# Remove numbers and special characters from the test string
cleaned_string = ''.join(filter(str.isalpha, test_string))
print(cleaned_string)
# Write the cleaned string into the shared memory segment
shm.buf[:len(cleaned_string)] = cleaned_string.encode('utf-8')
queue.put("Task 2 (Clean_Input) completed.")
print(f"C0 ({os.getpid()}): Task 2 (Clean_Input) completed.")
# Function for Task 3 (Find_Missing)
def find_missing(shm, queue):
print(f"P1 ({os.getpid()}): Task 3 (Find_Missing) started.")
queue.get() # Wait for Task 2 to complete
# Read the cleaned string from the shared memory
cleaned_string = shm.buf.tobytes().decode('utf-8')
# Find the missing alphabets
missing_alphabets = [ch for ch in string.ascii_lowercase if ch not in cleaned_string]
# Print the result
if missing_alphabets:
print(f"P1 ({os.getpid()}): Missing alphabets: {''.join(missing_alphabets)}")
else:
print(f"P1 ({os.getpid()}): No missing alphabets found.")
print(f"P1 ({os.getpid()}): Task 3 (Find_Missing) completed.")
if __name__ == '__main__':
# Create a pipe for communication between P0 and C0
parent_pipe, child_pipe = mp.Pipe()
# Create a shared memory segment
shm = mp.shared_memory.SharedMemory(create=True, size=1024)
# Create a queue to control the task execution order
task_queue = mp.Queue()
# Create P0 (Parent Process)
p0 = mp.Process(target=get_input, args=(parent_pipe, task_queue))
# Create C0 (Child Process)
c0 = mp.Process(target=clean_input, args=(child_pipe, shm, task_queue))
# Create P1 (Another Process)
p1 = mp.Process(target=find_missing, args=(shm, task_queue))
# Start the processes in the desired order
p0.start()
c0.start()
p1.start()
p1.join()
c0.join()
p0.join()
# Delete the shared memory segment
shm.close()
shm.unlink()
答: 暂无答案
评论