设为首页 加入收藏

TOP

一个简单的字符驱动程序
2014-11-18 16:29:54 】 浏览:8995
Tags:一个 简单 字符 驱动程序

  代码分为: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


  2#include


  3#include


  4#include


  5#include


  6#include


  7#include


  8#include


  9#include


  10#include


  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


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇UNREFERENCED_PARAMETER的作用 下一篇计算机二级辅导:合并排序

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目