探索Linux内核的内存管理机制,通过实践理解OOM(Out of Memory)killer的工作原理。
当系统内存严重不足时,Linux内核会触发OOM killer机制,选择并终止某些进程以释放内存。
结构体 | 描述 | 用途 |
---|---|---|
oom_device | 设备状态结构 | 存储分配的内存指针和统计信息 |
oom_ioctl_data | 控制参数 | 传递分配大小和模式参数 |
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#include <linux/slab.h>
#include <linux/oom.h>
#define OOM_IOC_MAGIC 'K'
#define OOM_ALLOC _IOW(OOM_IOC_MAGIC, 1, size_t)
struct oom_device {
void **allocated_ptrs;
size_t allocated_count;
size_t total_allocated;
};
static struct oom_device dev;
static long oom_ioctl(struct file *file, unsigned int cmd, unsigned long arg)
{
size_t size = arg;
void *ptr;
switch (cmd) {
case OOM_ALLOC:
ptr = kmalloc(size, GFP_KERNEL);
if (!ptr) return -ENOMEM;
dev.allocated_ptrs = krealloc(dev.allocated_ptrs,
(dev.allocated_count + 1) * sizeof(void *),
GFP_KERNEL);
dev.allocated_ptrs[dev.allocated_count++] = ptr;
dev.total_allocated += size;
printk(KERN_INFO "OOM: Allocated %zu bytes, total: %zu\n",
size, dev.total_allocated);
break;
default:
return -ENOTTY;
}
return 0;
}