Process.daemon = True 設置(必須在 start() 前)import os, time, sys
from multiprocessing import Process, current_process
def daemon_task():
p = current_process()
print(f"[{p.name}] Starting (PID: {p.pid})")
sys.stdout.flush()
time.sleep(3)
print(f"[{p.name}] Exiting") # 不會執行!
sys.stdout.flush()
if __name__ == "__main__":
p = Process(name="DaemonWorker", target=daemon_task)
p.daemon = True # 關鍵設置
p.start()
print("Main process sleeping 1s...")
time.sleep(1)
print("Main process exiting") # 此時守護進程被強制終止
輸出:
[DaemonWorker] Starting (PID: 12345)
Main process sleeping 1s...
Main process exiting
# 守護進程的 "Exiting" 不會打印
if __name__ == "__main__":
p = Process(name="DaemonWorker", target=daemon_task)
p.daemon = True
p.start()
# p.join() 會阻塞主進程,直到守護進程自然結束
p.join()
print("Main process exiting after daemon done")
輸出:
[DaemonWorker] Starting (PID: 12345)
[DaemonWorker] Exiting
Main process exiting after daemon done
| 特性 | 守護進程 (daemon=True) | 普通進程 (daemon=False) |
|---|---|---|
| 主進程退出行為 | 立即被終止 (SIGTERM) | 繼續運行直到完成 |
| join() 行為 | 可選,等待完成 | 必須調用,否則產生僵屍進程 |
| 典型用途 | 後台服務、監控、清理 | 核心業務任務、計算密集型 |
| 創建子進程 | 子進程自動為守護進程 | 子進程默認非守護 |
import multiprocessing
import time
import signal
import sys
class GracefulDaemon:
def __init__(self):
self.shutdown = multiprocessing.Event()
self.process = multiprocessing.Process(
target=self.run,
name="GracefulDaemon",
daemon=True
)
def run(self):
while not self.shutdown.is_set():
print("Daemon working...")
time.sleep(2)
print("Daemon shutdown gracefully")
def start(self):
self.process.start()
def stop(self, timeout=5):
self.shutdown.set()
self.process.join(timeout)
if self.process.is_alive():
print("Force terminating daemon")
self.process.terminate()
self.process.join()
if __name__ == "__main__":
daemon = GracefulDaemon()
daemon.start()
# 模擬主程序運行
time.sleep(6)
# 優雅停止
daemon.stop()
print("Main process done")
fork(),使用 spawn 啟動進程TerminateProcess 強制殺死p.daemon = True; p.start()SIGTERM/SIGINT 觸發優雅關閉合理使用守護進程能簡化後台任務管理,但務必理解其「隨主進程生死」的本質,避免數據丟失與資源洩漏。