编写内核模块程序,使用timer实现:在某个特定时刻,把当前占用内存最大的10个进程的信息按照占用内存递减的顺序进行打印。
#include "linux/init.h"
#include "linux/kernel.h"
#include "linux/module.h"
#include "linux/timer.h"
#include "linux/rtc.h"
#include "linux/time.h"
#include "linux/sched.h"
#include <linux/sched/signal.h>
#define K 10
struct topS_process{
char comm[10];
int pid;
int state;
long total_vm;
};
struct top_process topK[K];
static void process_copy(struct top_process *dst,struct top_process *src) {
strcpy(dst->comm,src->comm);
dst->pid=src->pid;
dst->state=src->state;
dst->total_vm=src->total_vm;
}
void sort(struct top_process top[],int k,struct top_process t) {
int i;
for(i=1;i<k;i++){
if(top[i].total_vm < t.total_vm){
process_copy(&top[i-1],&top[i]);
}else{
process_copy(&top[i-1],&t);
break;
}
}
if(i==k) {
process_copy(&top[i-1],&t);
}
}
void printTopK(struct timer_list *timer) {
int i;
struct task_struct *p;
struct top_process tmp;
for_each_process(p) {
if(p->mm!=NULL) {
if(p->mm->total_vm>topK[0].total_vm) {
strcpy(tmp.comm,p->comm);
tmp.pid=p->pid;
tmp.state=p->state;
tmp.total_vm=p->mm->total_vm;
sort(topK,K,tmp);
}
}
}
printk("top %d process using :\n",K);
for(i=K-1;i>=0;i--) {
printk("name:%s pid:%d state:%d mem:%ld \n",topK[i].comm,topK[i].pid,topK[i].state,topK[i].total_vm);
}
}
struct timer_list timer;
static int __init hello_init(void) {
int i;
for(i=0;i<10;i++){
topK[i].total_vm=i;
}
timer.expires=jiffies+5*HZ;
timer.function=printTopK;
add_timer(&timer);
return 0;
}
static void __exit hello_exit(void) {
printk(KERN_ALERT "Goodbye!\n");
}
module_init(hello_init);
module_exit(hello_exit);
MODULE_LICENSE("GPL");