Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

การสร้าง Child Process ด้วย fork() ใน Python

งานคือสร้าง child process และแสดง process ID ของทั้ง parent และ child โดยใช้ฟังก์ชัน fork() ใน Python

fork() สร้างกระบวนการลูกที่เป็นสำเนาของตัวเอง เป็นคอนเซปต์สำคัญของ UNIX/Linux ใช้สำหรับ multithreading environment การทำงานของ thread ถูกก๊อปปี้สร้าง child thread จาก parent thread

ค่าที่คืนของ fork():

  • ค่าลบ - เกิดข้อผิดพลาด
  • 0 - อยู่ใน child process
  • ค่าบวก - อยู่ใน parent process (ค่าคือ PID ของ child)

โมดูล fork() อยู่ใน os หรือ pty (pseudo-terminal)

ตัวอย่างที่ 1: ใช้ os.fork()


import os

def parentchild():
    n = os.fork()
    if n > 0:
        print("Parent process:", os.getpid())
    else:
        print("Child process:", os.getpid())

# Driver code
parentchild()

ผลลัพธ์


Parent process: 8023
Child process: 8024

ตัวอย่างที่ 2: ใช้ pty.fork() (Pseudo-terminal)

โมดูล pty จัดการ pseudo-terminal concepts ใช้เริ่มกระบวนการอื่น และอ่าน/เขียนจาก controlling terminal ได้

หมายเหตุ: ทำงานได้เฉพาะ UNIX-like systems (Linux, macOS) ไม่ทำงานบน Windows


import pty, os

def process_parent_child():
    (process_id, fd) = pty.fork()
    print("The Process ID for the Current process is:", os.getpid())
    print("The Process ID for the Child process is:", process_id)

process_parent_child()

ผลลัพธ์


The Process ID for the Current process is: 12508
The Process ID for the Child process is: 12509

ข้อสังเกตสำคัญ

  • os.fork() ทำงานได้บน Unix/Linux/macOS ไม่ทำงานบน Windows
  • บน Windows ใช้ multiprocessing.Process แทน (cross-platform)
  • หลัง fork() ทั้ง parent และ child จะรันคำสั่งถัดไปพร้อมกัน (parallel)
  • Child process ได้รับสำเนาของ memory space ของ parent (copy-on-write)
  • File descriptors ถูกสำเนา (shared offset) ต้องระวัง race conditions

เปรียบเทียบ: fork() vs multiprocessing.Process

คุณสมบัติos.fork()multiprocessing.Process
PlatformUnix onlyCross-platform
MemoryCopy-on-writeFresh interpreter
Overheadต่ำมากสูงกว่า
GILแยก process จริง ไม่มี GILแยก process จริง ไม่มี GIL