Chinaunix首页 | 论坛 | 博客
  • 博客访问: 169536
  • 博文数量: 69
  • 博客积分: 2627
  • 博客等级: 少校
  • 技术积分: 715
  • 用 户 组: 普通用户
  • 注册时间: 2008-10-24 22:37
文章分类

全部博文(69)

文章存档

2017年(3)

2014年(1)

2013年(4)

2012年(6)

2011年(21)

2010年(15)

2009年(19)

我的朋友

分类: LINUX

2010-01-04 14:30:10

scull.h
------------------

#ifndef __SCULL_H
#define __SCULL_H
#define SCULL_MAJOR 252
int scull_major=SCULL_MAJOR;
#endif


scull.c
------------------
#include
#include
#include
#include "scull.h"

MODULE_LICENSE("GPL");

int scull_open(struct inode *inode,struct file *filp);
int scull_release(struct inode *inode,struct file *filp);
int scull_read(struct file *filp,char *buf,size_t count,loff_t *f_pos);
int scull_write(struct file *filp,const char *buf,size_t count,loff_t *f_pos);

struct file_operations scull_fops={
    read:    scull_read,
    write:   scull_write,
    open:    scull_open,
    release: scull_release,
};


int init_module(void){
    int result;
    
    printk("<1> scull initilized.\n");

    result=register_chrdev(scull_major,"scull",&scull_fops);
    if(result<0){
        printk("<1> scull: can't get major %d\n",scull_major);
        return result;
    }

    if(scull_major==0) scull_major=result;
    printk("<1> major=%d\n",scull_major);
    return 0;
}

void cleanup_module(void){
    int result;
    printk("<1> when unload,major=%d\n",scull_major);
    result=unregister_chrdev(scull_major,"scull");
    if(result==-EINVAL)
      printk("<1> cleanup failed.");
    else
      printk("<1> scull removed.\n");
}


int scull_open(struct inode *inode,struct file *filp){
    printk("<1> scull opened.\n");
    MOD_INC_USE_COUNT;
    return 0;
}

int scull_release(struct inode *inode,struct file *filp){
    printk("<1> scull closed.\n");
    MOD_DEC_USE_COUNT;
    return 0;
}

int scull_read(struct file *filp,char *buf,size_t count,loff_t *f_pos){
    printk("<1> scull be called 'read'.\n");
    return 0;
}

int scull_write(struct file *filp,const char *buf,size_t count,loff_t *f_pos){
    printk("<1> scull be called 'write'.\n");
    return 0;
}




makefile
-----------------
KERNELDIR = /usr/src/linux-2.4.20-8

CFLAGS = -D__KERNEL__ -DMODULE -I$(KERNELDIR)/include -O -Wall
CC = gcc

all: scull.o
scull.o: scull.h
    $(CC) $(CFLAGS) -c scull.c



1.在上述源文件基础上编译生成scull.o文件,该文件即是生成的模块文件
2.本例中使用指定的主设备号(#define SCULL_MAJOR 252).
3.建立设备节点,该节点创建后永久存在,可用rm删除
  mknod /dev/scull c 252 0
4.向内核插入模块,建立模块与设备节点之间的关联.(不建立设备节点,将不能访问此模块的功能)
  insmod scull.o
  然后可在/proc/devices中查看到
5.使用/dev/scull
  读: cat /dev/scull
  写: ls > /dev/scull
6.rmmod scull
  删除模块

综上: 模块应与/dev中设备文件关联方可使用.本例中使用固定主设备号
      如果使用动态分配主设备号,将无法预先创建设备节点.
 
阅读(868) | 评论(0) | 转发(0) |
0

上一篇:编译内核的简单步骤

下一篇:关于ioctl

给主人留下些什么吧!~~