📄 smboldriver.cpp
字号:
#define __NO_VERSION__
#include <linux/modules.h>
#include <linux/version.h>
char kernel_version [] = UTS_RELEASE;
struct file_operations {
int (*seek) (struct inode * ,struct file *, off_t ,int);
int (*read) (struct inode * ,struct file *, char ,int);
int (*write) (struct inode * ,struct file *, off_t ,int);
int (*readdir) (struct inode * ,struct file *, struct dirent * ,int);
int (*select) (struct inode * ,struct file *, int ,select_table *);
int (*ioctl) (struct inode * ,struct file *, unsined int ,unsigned long);
int (*mmap) (struct inode * ,struct file *, struct vm_area_struct *);
int (*open) (struct inode * ,struct file *);
int (*release) (struct inode * ,struct file *);
int (*fsync) (struct inode * ,struct file *);
int (*fasync) (struct inode * ,struct file *,int);
int (*check_media_change) (struct inode * ,struct file *);
int (*revalidate) (dev_t dev);
}
/*
这个结构的每一个成员的名字都对应着一个系统调用.
用户进程利用系统调用在对设备文件进行诸如read/write操作时,
系统调用通过设备文件的主设备号找到相应的设备驱动程序,
然后读取这个数据结构相应的函数指针,接着把控制权交给该函数.
这是linux的设备驱动程序工作的基本原理.既然是这样,则编写设备驱
动程序的主要工作就是编写子函数,并填充file_operations的各个域.
*/
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/errno.h>
#include <asm/segment.h>
unsigned int test_major = 0;
static int read_test(struct inode *node,struct file *file,
char *buf,int count)
{
int left;
if (verify_area(VERIFY_WRITE,buf,count) == -EFAULT )
return -EFAULT;
for(left = count ; left > 0 ; left--)
{
__put_user(1,buf,1);
buf++;
}
return count;
}
static int write_tibet(struct inode *inode,struct file *file,
const char *buf,int count)
{
return count;
}
static int open_tibet(struct inode *inode,struct file *file )
{
MOD_INC_USE_COUNT;
return 0;
}
static void release_tibet(struct inode *inode,struct file *file )
{
MOD_DEC_USE_COUNT;
}
/* 这几个函数都是空操作.实际调用发生时什么也不做,
他们仅仅为下面的结构提供函数指针。
*/
struct file_operations test_fops = {
NULL,
read_test,
write_test,
NULL, /* test_readdir */
NULL,
NULL, /* test_ioctl */
NULL, /* test_mmap */
open_test,
release_test, NULL, /* test_fsync */
NULL, /* test_fasync */
/* nothing more, fill with NULLs */
};
/* 设备驱动程序的主体可以说是写好了。现在要把驱动程序嵌入内核。
驱动程序可以按照两种方式编译。一种是编译进kernel,另一种是编译成
模块(modules),如果编译进内核的话,会增加内核的大小,还要改动内核
的源文件,而且不能动态的卸载,不利于调试,所以推荐使用模块方式
。
*/
int init_module(void)
{
int result;
result = register_chrdev(0, "test", &test_fops);
if (result < 0) {
printk(KERN_INFO "test: can't get major number\n");
return result;
}
if (test_major == 0) test_major = result; /* dynamic */
return 0;
}
void cleanup_module(void)
{
unregister_chrdev(test_major, "test");
}
/* 在用insmod命令将编译好的模块调入内存时,init_module 函数被调用。
在这里,init_module只做了一件事,就是向系统的字符设备表登记了一个
字符设备。register_chrdev需要三个参数,参数一是希望获得的设备号,如果
是零的话,系统将选择一个没有被占用的设备号返回。参数二是设备
文件名,参数三用来登记驱动程序实际执行操作的函数的指针。
如果登记成功,返回设备的主设备号,不成功,返回一个负值。
void cleanup_module(void)
{
unregister_chrdev(test_major, "test");
}
在用rmmod卸载模块时,cleanup_module函数被调用,它释放字符设
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -