Linux内核定时器

编写内核模块程序,使用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"); 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值