• 获取主进程和子进程编号os.getpid()
    • 在子进程内获取他的父进程编号os.getppid()
    • 通过进程编号停止进程os.kill(process_id, 9)
    1. import multiprocessing
    2. import time
    3. import os
    4. def dance():
    5. dance_process_id = os.getpid()
    6. print("dance进程编号: ", dance_process_id, multiprocessing.current_process)
    7. dance_process_parent_id = os.getppid()
    8. print("dance父进程编号: ", dance_process_parent_id)
    9. for item in range(1, 5):
    10. print("跳舞...")
    11. time.sleep(0.2)
    12. # 9 表示强行停止该进程
    13. os.kill(dance_process_id, 9)
    14. pass
    15. pass
    16. def sing():
    17. sing_process_id = os.getpid()
    18. print("sing进程编号: ", sing_process_id, multiprocessing.current_process)
    19. for item in range(1, 5):
    20. print("唱歌...")
    21. time.sleep(0.2)
    22. pass
    23. pass
    24. if __name__ == "__main__":
    25. dance_process = multiprocessing.Process(target=dance)
    26. sing_process = multiprocessing.Process(target=sing)
    27. dance_process.start()
    28. sing_process.start()
    29. main_processs_id = os.getpid()
    30. print("主进程编号: ", main_processs_id, multiprocessing.current_process)