编写模块遍历系统中的进程

编写内核模块实现进程的遍历。这个有点类似ps命令了。

  源程序:list.c

  /*****************************************

  *功能:利用进程链表遍历当前系统中的所有进程

  *同时可以打印出进程的相关信息

  *

  * ***************************************/

  #include <linux /list.h>

  #include <linux /module.h>

  #include <linux/init.h>

  #include <linux/sched.h>

  #define METHOD 2

  static int list_init(void)

  {

  struct task_struct *task, *p;

  struct list_head *pos;

  int count;

  char *method;

  count = 0; /*下面这些初始化完全是为了消除编译时的警告信息*/

  p = NULL;

  task = NULL;

  pos = NULL;

  method = NULL;

  task = &init_task;

  printk(KERN_ALERT"PID/tCOMM/n");

  switch(METHOD) {

  case 1:

  method="list_for_each";

  break;

  case 2:

  method="for_each_process";

  break;

  case 3:

  method="list_for_each_entry";

  break;

  }

  printk( "The method is %s/n", method );

  #if METHOD == 1

  list_for_each( pos, &task->tasks ) {

  p = list_entry( pos, struct task_struct, tasks );

  count++;

  printk( KERN_ALERT "%d/t%s/n", p->pid, p->comm );

  }

  #elif METHOD == 2

  for_each_process(task) {

  count++;

  printk( KERN_ALERT "%d/t%s/n", task->pid, task->comm );

  }

  #elif METHOD == 3

  list_for_each_entry( p, &task->tasks, tasks ) {

  count++;

  printk( KERN_ALERT "%d/t%s/n", p->pid, p->comm );

  }

  #endif

  printk("系统当前共 %d 个进程!!", count);

  return 0;

  }

  static void list_exit(void)

  {

  printk( KERN_ALERT "GOOD BYE!!/n");

  }

  module_init( list_init );

  module_exit( list_exit );

  MODULE_AUTHOR( "Along" );

  MODULE_LICENSE( "GPL" );

  我的Makefile:

  obj-m := list.o

  KERNELDIR ?= /lib/modules/$(shell uname -r)/build

  PWD := $(shell pwd)

  all:

  make -C $(KERNELDIR) M=$(PWD) modules

  clean:

  make -C $(KERNELDIR) M=$(PWD) clean

  这个程序主要用到了几个关键的宏list_for_each,list_for_each_entry,for_each_process 。我们可以通过修改程序中 METHOD 的值查看不同宏运行产生的结果。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值