linux内核demo

1,hello:
最基本的hello world内核模块
make
sudo insmod hello.ko
dmesg |tail
sudo rmmod hello

/*************** hello.c ***************/
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
MODULE_LICENSE("Dual BSD/GPL");
MODULE_AUTHOR("djwow");


static int hello_init(void)
{
  printk(KERN_ALERT "Hello, world!\n");
  return 0;
}


static void hello_exit(void)
{
  printk(KERN_ALERT "Goodbye, My Dear World!\n");
}


module_init(hello_init);
module_exit(hello_exit);






makefile:
obj-m = hello.o
KVERSION = $(shell uname -r)
all:
	make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
	make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean





2,hello-1,hello-2:
hello-2导出了一个hello_data的全局变量,供hello-1中的模块使用。
先编译hello-2。并将目录下的Module.symvers拷贝到hello-1中。然后再编译hello-1。
然后先安装hello-2中的模块,再运行hello-1中的模块。
或者将hello-1中的KBUILD_EXTRA_SYMBOLS = /mnt/hgfs/MallocFreeIBM/Linux/10ten-hellokernel/demo/hello-2/Module.symvers中的/mnt/hgfs/MallocFreeIBM/Linux/10ten-hellokernel/demo/hello-2修改为你自己对应的hello-2的路径。


hello-1.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>


MODULE_LICENSE("GPL");
extern int hello_data;


static int hello_init(void)
{
	printk(KERN_ERR "hello,kernel!,this is hello module\n");
	printk(KERN_ERR "hello_data:%d\n",++hello_data);
	return 0;
}


static void hello_exit(void)
{
	printk(KERN_ERR "hello_data:%d\n",--hello_data);
	printk(KERN_ERR "Leave hello module!\n");
}
module_init(hello_init);
module_exit(hello_exit);


MODULE_AUTHOR("djwow");
MODULE_DESCRIPTION("This is hello module");
MODULE_ALIAS("A simple example");



hello_2.c
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>


MODULE_LICENSE("GPL");
unsigned int hello_data=100;
EXPORT_SYMBOL(hello_data);


static int hello_h_init(void)
{
	hello_data+=5;
	printk(KERN_ERR "hello_data:%d\nhello kernel,this is hello_h module\n",hello_data);


	return 0;
}


static void hello_h_exit(void)
{
	hello_data-=5;
	printk(KERN_ERR "hello_data:%d\nleave hello_h module\n",hello_data);
}


module_init(hello_h_init);
module_exit(hello_h_exit);
MODULE_AUTHOR("djwow.com");


makefile
obj-m=hello_2.o
KVERSION = $(shell uname -r)
all:
	make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
	make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean


3,hello-param用于向模块动态传递参数
编译之后运行方法:
insmod hello who="world" times=5 


#include <linux/init.h>
#include <linux/module.h>
#include <linux/moduleparam.h>  
      
MODULE_LICENSE("Dual BSD/GPL");     


static char *who= "world";             
static int times = 1; 
      
module_param(times,int,S_IRUSR);     
module_param(who,charp,S_IRUSR);   


static int hello_init(void)       
{
    int i;
    for(i=0;i<times;i++)
       printk(KERN_ALERT "(%d) hello, %s!\n",i,who);
     return 0;
}


static void hello_exit(void) 
{
    printk(KERN_ALERT"Goodbye, %s!\n",who);
}


module_init(hello_init);
module_exit(hello_exit);

makefile:
obj-m = hello.o
KVERSION = $(shell uname -r)
all:
	make -C /lib/modules/$(KVERSION)/build M=$(PWD) modules
clean:
	make -C /lib/modules/$(KVERSION)/build M=$(PWD) clean


4,kernel-client 通信demop 顺便演示了timer使用
先分别运行make编译好client和kernel程序。
然后,加载驱动:sudo insmod timer-kernel.ko 
然后,
cat /proc/devices,查看second对应的主功能号,如251
sudo mknod /dev/second c 251 0
然后运行client:
./timer-client


client:
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>


int main(void)
{
    int fd, i;
    int data;
    fd = open("/dev/second",O_RDONLY);
    if (fd < 0)
    {
        printf("open /dev/second error\n");
    }
    for(i = 0; ; i++)
    {
      read(fd, &data, sizeof(data));
      printf("read /dev/second is %d\n",data);
      sleep(1);
       }
    close(fd);
}


makefile:
timer-client:timer-client.o
	gcc -o timer-client timer-client.o
timer-client.o:timer-client.c
	gcc -c timer-client.c -o timer-client.o
clean:
	rm -f *.o timer-client

kernel:
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>
#include <linux/timer.h>
#include <asm/atomic.h>


#define SECOND_MAJOR 0


static int second_major = SECOND_MAJOR;


struct second_dev
{
    struct cdev cdev;
    atomic_t counter;
    struct timer_list s_timer;
};


struct second_dev *second_devp;


static void second_timer_handle(unsigned long arg)
{
    mod_timer(&second_devp->s_timer, jiffies + HZ);
    atomic_inc(&second_devp->counter);
    
    printk(KERN_INFO "current jiffies is %ld\n",jiffies);
}


int second_open(struct inode *inode, struct file *filp)
{
  init_timer(&second_devp->s_timer);
  second_devp->s_timer.function = &second_timer_handle;
  second_devp->s_timer.expires = jiffies + HZ;
  
  add_timer(&second_devp->s_timer);
  atomic_set(&second_devp->counter, 0);
  return 0;    
}


int second_release(struct inode *inode, struct file *filp)
{
    del_timer(&second_devp->s_timer);
    
    return 0;
}
static ssize_t second_read(struct file *filp, char __user *buf, size_t count, 
  loff_t *ppos)
{
    int counter;
    
    counter = atomic_read(&second_devp->counter);
    if (put_user(counter, (int *)buf))
    {
        return -EFAULT;
    }else
    {
        return sizeof(unsigned int);
    }
    
}


static const struct file_operations second_fops =
{
    .owner = THIS_MODULE,
    .open = second_open,
    .release = second_release,
    .read = second_read,
};
static void second_setup_cdev(struct second_dev *dev, int index)
{
    int err, devno = MKDEV(second_major, index);
    cdev_init(&dev->cdev, &second_fops);
    dev->cdev.owner = THIS_MODULE;
    dev->cdev.ops = &second_fops;
    err = cdev_add(&dev->cdev, devno, 1);
    if (err)
    {
        printk(KERN_NOTICE "Error %d add second%d", err, index);
    }
}
int second_init(void)
{
    int ret;
    dev_t devno = MKDEV(second_major, 0);
    
    if (second_major)
    {
        ret = register_chrdev_region(devno, 1, "second");
    }else
    {
        ret = alloc_chrdev_region(&devno, 0, 1, "second");
        second_major = MAJOR(devno);
    }
    if (ret < 0)
    {
        return ret;
    }
    
    second_devp = kmalloc(sizeof(struct second_dev), GFP_KERNEL);
    if (!second_devp)
    {
        ret = -ENOMEM;
        goto fail_malloc;
    }
    
    memset(second_devp, 0, sizeof(struct second_dev));
    
    second_setup_cdev(second_devp, 0);
    
    return 0;


  fail_malloc:
      unregister_chrdev_region(devno, 1);
      return ret;
}


void second_exit(void)
{
    cdev_del(&second_devp->cdev);
    kfree(second_devp);
    unregister_chrdev_region(MKDEV(second_major, 0), 1);
}


MODULE_AUTHOR("djwow");
MODULE_LICENSE("Dual BSD/GPL");


module_param(second_major, int, S_IRUGO);


module_init(second_init);
module_exit(second_exit);


5,char_drv 通信demo 

另外一个例子可以看我了另一篇文件

http://blog.csdn.net/zhuhuibeishadiao/article/details/51456791


先运行make编译好kernel程序。
然后,加载驱动:sudo insmod char_drv.ko
然后,
cat /proc/devices,查看mem_dev对应的主功能号,如251
sudo mknod /dev/memdev0 c 251 0
然后运行client:
gcc -o test_char_drv test_char_drv.c 
./test_char_drv


R3:
#include <stdio.h>
#include <string.h>


int main()
{
    FILE *fp0 = NULL;
    char Buf[4096];
    
    /*初始化Buf*/
    strcpy(Buf,"Mem is char dev!");
    printf("BUF: %s\n",Buf);
    
    /*打开设备文件*/
    fp0 = fopen("/dev/memdev0","r+");
    if (fp0 == NULL)
    {
        printf("Open Memdev0 Error!\n");
        return -1;
    }
    
    /*写入设备*/
    fwrite(Buf, sizeof(Buf), 1, fp0);
    
    /*重新定位文件位置(思考没有该指令,会有何后果)*/
    fseek(fp0,0,SEEK_SET);
    
    /*清除Buf*/
    strcpy(Buf,"Buf is NULL!");
    printf("BUF: %s\n",Buf);
    
    
    /*读出设备*/
    fread(Buf, sizeof(Buf), 1, fp0);
    
    /*检测结果*/
    printf("BUF: %s\n",Buf);
    
    return 0;    


}


R0:
char_drv.h
#ifndef _MEMDEV_H_
#define _MEMDEV_H_


#ifndef MEMDEV_MAJOR
#define MEMDEV_MAJOR 251   /*预设的mem的主设备号*/
#endif


#ifndef MEMDEV_NR_DEVS
#define MEMDEV_NR_DEVS 2    /*设备数*/
#endif


#ifndef MEMDEV_SIZE
#define MEMDEV_SIZE 4096
#endif


/*mem设备描述结构体*/
struct mem_dev                                     
{                                                        
  char *data;                      
  unsigned long size;       
};


#endif /* _MEMDEV_H_ */

char_drv.c

#include "char_drv.h"
#include <linux/module.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/errno.h>
#include <linux/mm.h>
#include <linux/sched.h>
#include <linux/init.h>
#include <linux/cdev.h>
#include <asm/io.h>
#include <asm/system.h>
#include <asm/uaccess.h>


static int mem_major = MEMDEV_MAJOR;


module_param(mem_major, int, S_IRUGO);


struct mem_dev *mem_devp; /*设备结构体指针*/


struct cdev cdev; 


/*文件打开函数*/
int mem_open(struct inode *inode, struct file *filp)
{
    struct mem_dev *dev;
    
    /*获取次设备号*/
    int num = MINOR(inode->i_rdev);


    if (num >= MEMDEV_NR_DEVS) 
            return -ENODEV;
    dev = &mem_devp[num];
    
    /*将设备描述结构指针赋值给文件私有数据指针*/
    filp->private_data = dev;
    
    return 0; 
}


/*文件释放函数*/
int mem_release(struct inode *inode, struct file *filp)
{
  return 0;
}


/*读函数*/
static ssize_t mem_read(struct file *filp, char __user *buf, size_t size, loff_t *ppos)
{
  unsigned long p =  *ppos;        /*记录文件指针偏移位置*/  
  unsigned int count = size;    /*记录需要读取的字节数*/ 
  int ret = 0;    /*返回值*/  
  struct mem_dev *dev = filp->private_data; /*获得设备结构体指针*/


  /*判断读位置是否有效*/
  if (p >= MEMDEV_SIZE)    /*要读取的偏移大于设备的内存空间*/  
    return 0;
  if (count > MEMDEV_SIZE - p)     /*要读取的字节大于设备的内存空间*/ 
    count = MEMDEV_SIZE - p;


  /*读数据到用户空间:内核空间->用户空间交换数据*/  
  if (copy_to_user(buf, (void*)(dev->data + p), count))
  {
    ret =  - EFAULT;
  }
  else
  {
    *ppos += count;
    ret = count;
    
    printk(KERN_INFO "read %d bytes(s) from %ld\n", count, p);
  }


  return ret;
}


/*写函数*/
static ssize_t mem_write(struct file *filp, const char __user *buf, size_t size, loff_t *ppos)
{
  unsigned long p =  *ppos;
  unsigned int count = size;
  int ret = 0;
  struct mem_dev *dev = filp->private_data; /*获得设备结构体指针*/
  
  /*分析和获取有效的写长度*/
  if (p >= MEMDEV_SIZE)
    return 0;
  if (count > MEMDEV_SIZE - p)    /*要写入的字节大于设备的内存空间*/
    count = MEMDEV_SIZE - p;
    
  /*从用户空间写入数据*/
  if (copy_from_user(dev->data + p, buf, count))
    ret =  - EFAULT;
  else
  {
    *ppos += count;      /*增加偏移位置*/  
    ret = count;      /*返回实际的写入字节数*/ 
    
    printk(KERN_INFO "written %d bytes(s) from %ld\n", count, p);
  }


  return ret;
}


/* seek文件定位函数 */
static loff_t mem_llseek(struct file *filp, loff_t offset, int whence)
{ 
    loff_t newpos;      


    switch(whence) {
      case 0: /* SEEK_SET */       /*相对文件开始位置偏移*/ 
        newpos = offset;           /*更新文件指针位置*/
        break;


      case 1: /* SEEK_CUR */
        newpos = filp->f_pos + offset;    
        break;


      case 2: /* SEEK_END */
        newpos = MEMDEV_SIZE -1 + offset;
        break;


      default: /* can't happen */
        return -EINVAL;
    }
    if ((newpos<0) || (newpos>MEMDEV_SIZE))
        return -EINVAL;
        
    filp->f_pos = newpos;
    return newpos;


}


/*文件操作结构体*/
static const struct file_operations mem_fops =
{
  .owner = THIS_MODULE,
  .llseek = mem_llseek,
  .read = mem_read,
  .write = mem_write,
  .open = mem_open,
  .release = mem_release,
};


/*设备驱动模块加载函数*/
static int memdev_init(void)
{
  int result;
  int i;


  dev_t devno = MKDEV(mem_major, 0);


   /* 申请设备号,当xxx_major不为0时,表示静态指定;当为0时,表示动态申请*/ 
  /* 静态申请设备号*/
  if (mem_major)
    result = register_chrdev_region(devno, 2, "mem_dev");
  else  /* 动态分配设备号 */
  {
    result = alloc_chrdev_region(&devno, 0, 2, "mem_dev");
    mem_major = MAJOR(devno);    /*获得申请的主设备号*/
  }  
  
  if (result < 0)
    return result;


 /*初始化cdev结构,并传递file_operations结构指针*/ 
  cdev_init(&cdev, &mem_fops);    
  cdev.owner = THIS_MODULE;    /*指定所属模块*/
  cdev.ops = &mem_fops;
  
  /* 注册字符设备 */
  cdev_add(&cdev, MKDEV(mem_major, 0), MEMDEV_NR_DEVS);
   
  /* 为设备描述结构分配内存*/
  mem_devp = kmalloc(MEMDEV_NR_DEVS * sizeof(struct mem_dev), GFP_KERNEL);
  if (!mem_devp)    /*申请失败*/
  {
    result =  - ENOMEM;
    goto fail_malloc;
  }
  memset(mem_devp, 0, sizeof(struct mem_dev));
  
  /*为设备分配内存*/
  for (i=0; i < MEMDEV_NR_DEVS; i++) 
  {
        mem_devp[i].size = MEMDEV_SIZE;
        mem_devp[i].data = kmalloc(MEMDEV_SIZE, GFP_KERNEL);
        memset(mem_devp[i].data, 0, MEMDEV_SIZE);
  }
    
  return 0;


  fail_malloc: 
  unregister_chrdev_region(devno, 1);
  
  return result;
}


/*模块卸载函数*/
static void memdev_exit(void)
{
  cdev_del(&cdev);   /*注销设备*/
  kfree(mem_devp);     /*释放设备结构体内存*/
  unregister_chrdev_region(MKDEV(mem_major, 0), 2); /*释放设备号*/
}


MODULE_AUTHOR("djwow");
MODULE_LICENSE("GPL");


module_init(memdev_init);
module_exit(memdev_exit);


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值