Chinaunix

标题: 简单的scull [打印本页]

作者: 2195113    时间: 2008-10-21 16:50
标题: 简单的scull

                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(" scull initilized.\n");
    result=register_chrdev(scull_major,"scull",&scull_fops);
    if(result scull: can't get major %d\n",scull_major);
        return result;
    }
    if(scull_major==0) scull_major=result;
    printk(" major=%d\n",scull_major);
    return 0;
}
void cleanup_module(void){
    int result;
    printk(" when unload,major=%d\n",scull_major);
    result=unregister_chrdev(scull_major,"scull");
    if(result==-EINVAL)
      printk(" cleanup failed.");
    else
      printk(" scull removed.\n");
}
int scull_open(struct inode *inode,struct file *filp){
    printk(" scull opened.\n");
    MOD_INC_USE_COUNT;
    return 0;
}
int scull_release(struct inode *inode,struct file *filp){
    printk(" 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(" scull be called 'read'.\n");
    return 0;
}
int scull_write(struct file *filp,const char *buf,size_t count,loff_t *f_pos){
    printk(" 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中设备文件关联方可使用.本例中使用固定主设备号
      如果使用动态分配主设备号,将无法预先创建设备节点.

               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u/26390/showart_1331436.html




欢迎光临 Chinaunix (http://bbs.chinaunix.net/) Powered by Discuz! X3.2