โมดูล resource ใช้วัดและควบคุม Resource Usage ของ Process ใน UNIX (CPU Time, Memory, File Descriptors, etc.)
import resource
Resource Limits (การจำกัดทรัพยากร)
มี 2 ระดับ:
- Soft Limit: ขีดจำกัดปัจจุบัน แก้ไขได้ แต่ไม่เกิน Hard Limit
- Hard Limit: ขีดจำกัดสูงสุด ลดได้ แต่เพิ่มไม่ได้ (ต้อง Root)
เมธอดหลัก
getrlimit(resource)- คืน (soft, hard)setrlimit(resource, (soft, hard))- ตั้งค่า Limitprlimit(pid, resource[, limits])- Get/Set พร้อมกัน (PID=0 = Current Process)
Resource Constants สำคัญ
| Constant | คำอธิบาย |
|---|---|
| RLIMIT_CPU | CPU Time สูงสุด (วินาที) - เกินได้ Signal SIGXCPU |
| RLIMIT_DATA | Heap Size สูงสุด |
| RLIMIT_STACK | Stack Size สูงสุด |
| RLIMIT_NOFILE | Open File Descriptors สูงสุด |
| RLIMIT_MEMLOCK | Locked Memory สูงสุด |
| RLIMIT_NPROC | Process สูงสุดต่อ User |
| RLIMIT_AS | Address Space สูงสุด (Virtual Memory) |
| RLIM_INFINITY | ไม่จำกัด |
Resource Usage (การใช้ทรัพยากร)
resource.getrusage(who)
คืน Object มีฟิลด์:
ru_utime- User CPU Timeru_stime- System CPU Timeru_maxrss- Max Resident Set Size (KB)ru_minflt/ru_majflt- Page Faultsru_nswap- Swap Countru_inblock/ru_oublock- Block I/Oru_nvcsw/ru_nivcsw- Context Switches
Who Constants
| Constant | ความหมาย |
|---|---|
| RUSAGE_SELF | Process ปัจจุบัน (รวม Threads) |
| RUSAGE_CHILDREN | Child Processes |
| RUSAGE_BOTH | Self + Children (ไม่รองรับทุก OS) |
| RUSAGE_THREAD | Current Thread เท่านั้น (Linux 2.6.26+) |
โค้ดตัวอย่าง
import resource
# ดู Resource Usage
usage = resource.getrusage(resource.RUSAGE_SELF)
print(usage)
print('Page Size:', resource.getpagesize())
# จำกัด CPU Time 1 วินาที (Soft), 2 วินาที (Hard)
resource.setrlimit(resource.RLIMIT_CPU, (1, 2))
print('CPU Limits:', resource.getrlimit(resource.RLIMIT_CPU))
# Loop หนักเพื่อทดสอบ
for a in range(1000):
for b in range(1000):
for c in range(1000):
pass
ผลลัพธ์
resource.struct_rusage(ru_utime=0.035801, ru_stime=0.01074, ru_maxrss=9356, ...) Page Size: 4096 CPU Limits: (1, 2) CPU time limit exceeded (core dumped)
การประยุกต์ใช้
- ป้องกัน Process รันนานเกินไป (Runaway Process)
- จำกัด Memory ป้องกัน OOM Killer
- Monitoring/Profiling Performance
- Sandboxing Untrusted Code