linux 添加内核模块

模块是LINUX特有的一种机制,可以动态的增加内核的功能

可以作为独立程序来编译,但可以随时被链接到内核中,成为内核的一部分(INSMOD ./[模块名].ko),也可以被卸载(RMMOD ./[模块名].ko),模块简单灵活,相比系统调用,避免了编译和启动内核的麻烦,却一样可以再和心态工作。

 

下面写写个例子

 

列出某进程家族的信息,包括子进程,兄弟进程,和子进程

输出程序名,PID号。

 

下面用到两个宏list_entry 和list_for_each

详细用法请参看LINUX-KERNEL 2。4 的文档

#include <linux/init.h>
#include<linux/module.h>
#include<linux/sched.h>
#include<linux/string.h>
#include <linux/prefetch.h>
MODULE_LICENSE("GPL");
static int tpid=1;
module_param(tpid, int, S_IRUGO);
MODULE_PARM_DESC(tpid, "The pid of the task");


static int list_family_init(void){

 
 struct task_struct *task_ptr=find_task_by_pid(tpid);
 //*******************************************Father!!******************************************************************//
 printk(KERN_ALERT"Task father info :/n/t Father PID =  %ld  is executing program %s /n",task_ptr->parent->pid,task_ptr->parent->comm);

 

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

 

 //*******************************************Children!!***************************************************************//
   /*  list_entry(task_ptr,task_struct,children);
     struct list_head *pos;
     struct list_head *head=task_ptr->children; 

     for (pos = (head)->next; prefetch(pos->next), pos != (head);pos = pos->next)
     {
      printk(KERN_ALERT"Task children info :/n/t Children PID = %d is executing program %s /n",pos->pid,pos->comm);
     }
   */ 

 struct list_head * temp_ptr;
 struct task_struct *p;
 //struct list_head  tptr=task_ptr->children.next;

 list_for_each(temp_ptr,&task_ptr->children){
  p=list_entry(temp_ptr,struct task_struct,sibling);
  printk(KERN_ALERT"Task children info :/n/t Children PID = %d is executing program %s /n",p->pid,p->comm);
 }

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

 


 //***********************************************Brother!!**************************************************************//
 
 struct list_head * temp_bro_ptr;
 struct task_struct *p_for_bro;

 list_for_each(temp_bro_ptr,&task_ptr->sibling){
  p_for_bro=list_entry(temp_bro_ptr,struct task_struct,sibling);
  printk(KERN_ALERT"Task Brother info :/n/t Brother PID = %d is executing program %s /n",p_for_bro->pid,p_for_bro->comm);
 }

  
 return 0;
}

static void list_family_exit(void)
{
 printk(KERN_ALERT"Goodbye  task 2 !/n");
}
module_init(list_family_init);
module_exit(list_family_exit);

然后写一个MAKEFILE文件可以测试一下

我们默认是用一号进程传进去

最后可以看到运行的结果。

 

我也在学习这些内核的调用,这次的收获最大的地方是感觉应该多看一些英文的文档,他们做的真的很细致

大家共勉吧!

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值