一个简单的字符驱动程序实例
来源:优易学  2011-11-30 17:48:19   【优易学:中国教育考试门户网】   资料下载   IT书店

  代码分为:makefile ,内核态程序 globalmem.c 用户态程序 user.c 功能是把一个数组排序,你也可以使用 read write函数往内存里写东西。

  运行方法:

  make,产生globalmem.ko文件, Insmod globalmem.ko ,  看一下 dmesg -c 是否有提示信息(也可以 lsmod | grep "glo"), 有的话说明加载上了,

  然后 mknod /dev globalmem c 254 0 , 看一下 ls /proc/device/ | grep "glo" 有东西没。

  然后运行用户态程序,数组被排序了。dmesg -c 可以看到提示信息, 在模块中排序了。

  上代码(是带锁的代码,顺便练练手)

  makefile

  1# makefile for kernel 2.6

  2ifneq ($(KERNELRELEASE),)

  3#mymodule-objs := file1.o file2.o

  4obj-m := globalmem.o

  5

  6else

  7PWD  := $(shell pwd)

  8KVER := $(shell uname -r)

  9KDIR := /lib/modules/$(KVER)/build

  10all:

  11  $(MAKE) -C $(KDIR) M=$(PWD)

  12clean:

  13  rm -rf .*.cmd *.o *.mod.c *.ko .tmp_versions

  14

  15endif

  16

  内核模块

  1#include <linux/module.h>

  2#include <linux/types.h>

  3#include <linux/errno.h>

  4#include <linux/mm.h>

  5#include <linux/sched.h>

  6#include <linux/version.h>

  7#include <linux/cdev.h>

  8#include <asm/io.h>

  9#include <asm/system.h>

  10#include <asm/uaccess.h>

  11#include "mem.h"

  12

  13#define GLOBALMEM_SIZE      0x1000

  14#define MEM_CLEAR      0x1

  15#define ARRAY_INSTER      0x2

  16#define GLOBALMEM_MAJOR      254

  17

  18static int globalmem_major = GLOBALMEM_MAJOR;

  19

  20//the struct of global

  21typedef struct __globalmem_dev{

  22  struct cdev   cdev;

  23  unsigned char  mem[GLOBALMEM_SIZE];

  24  //add lock, signal

  25  struct semaphore sem;

  26  atomic_t  ato;

  27}globalmem_dev;

  28

  29globalmem_dev * global;

  30

  31typedef struct __arithmetic_st{

  32  int  buf[10];

  33  int len;

  34}arithmetic_st;

  35

  36

  37

  38

  39int globalmem_open(struct inode *inode, struct file * filp)

  40{

  41  filp->private_data = global;

  42  //you can only open one file

  43  if(!atomic_dec_and_test(&global->ato))

  44  {

  45      printk( KERN_NOTICE "atomic is lock\n");

  46      return -EBUSY;

  47  }

  48  return 0;

  49}

  50

  51int globalmem_release(struct inode * inode, struct file * filp)

  52{

  53  atomic_inc(&global->ato);

  54  return 0;

  55}

  56

  57

  58//read

[1] [2] [3] [4] 下一页

责任编辑:小草

文章搜索:
 相关文章
热点资讯
资讯快报
热门课程培训