Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Python

Tạo tiến trình con với fork() trong Python

Hàm os.fork() (Unix/Linux) tạo tiến trình con bằng cách nhân bản tiến trình cha. Trả về PID trong cha, 0 trong con, âm nếu lỗi.

Cơ chế fork()

  • Tiến trình con là bản sao gần như hoàn hảo của cha (memory, file descriptor, register...).
  • Copy-on-write: trang nhớ chỉ copy khi ghi.
  • Cả hai tiếp tục chạy từ dòng sau fork().

Ví dụ cơ bản với os.fork()

import os

def parent_child():
    pid = os.fork()
    if pid > 0:
        print(f"Parent process: PID={os.getpid()}, Child PID={pid}")
    elif pid == 0:
        print(f"Child process: PID={os.getpid()}, Parent PID={os.getppid()}")
    else:
        print("Fork failed!")

parent_child()

Kết quả

Parent process: PID=8023, Child PID=8024
Child process: PID=8024, Parent PID=8023

Sử dụng pty.fork() (pseudo-terminal)

import pty, os

def demo_pty():
    pid, fd = pty.fork()
    print(f"Current PID: {os.getpid()}")
    print(f"Child PID: {pid}")
    # fd: file descriptor của pseudo-terminal (chỉ trong parent)

demo_pty()

Lưu ý quan trọng

  • Chỉ hoạt động trên Unix/Linux/macOS. Windows không hỗ trợ fork() (dùng multiprocessing hoặc subprocess).
  • Sau fork(), tránh thao tác I/O phức tạp trước exec() (deadlock risk).
  • Thường dùng pattern: fork() → exec() để chạy chương trình khác.
  • Trong Python, multiprocessing.Process dùng spawn/forkserver trên Windows, fork trên Unix.

Ví dụ fork + exec

import os

pid = os.fork()
if pid == 0:
    # Child: thay thế tiến trình bằng ls
    os.execlp('ls', 'ls', '-l')
else:
    # Parent: chờ con kết thúc
    os.waitpid(pid, 0)
    print("Child finished")