入门文章:教你学会编写Linux设备驱动之三
文章作者 100test 发表时间 2007:03:14 16:20:23
来源 100Test.Com百考试题网
static int asdf_open (struct inode *inode, struct file *filp).
static int asdf_release (struct inode *inode, struct file *filp).
static ssize_t asdf_read (struct file *filp, char *buf, size_t count,loff_t *f_pos).
static ssize_t asdf_write (struct file *filp, const char *buf, size_t count,loff_t *f_pos).
static loff_t asdf_lseek (struct file * file, loff_t offset, int orig).
/* 申请主设备号时用的结构, 在linux/fs.h里定义 */
struct file_operations asdf_fops = {
open: asdf_open,
release: asdf_release,
read: asdf_read,
write: asdf_write,
llseek: asdf_lseek,
}.
static int asdf_major. /* 用来保存申请到的主设备号 */
static u8 asdf_body[4096]="asdf_body\n". /* 设备 */
static int
init_module
(){
printk ("Hi, This A Simple Device File!\n").
asdf_major = register_chrdev (0, "A Simple Device File", &.asdf_fops). /* 申请字符设备的主设备号 */
if (asdf_major < 0) return asdf_major. /* 申请失败就直接返回错误编号 */
printk ("The major is:%d\n", asdf_major). /* 显示申请到的主设备号 */
return 0. /* 模块正常初始化 */
}
static void
cleanup_module
(){
unregister_chrdev(asdf_major, "A Simple Device File"). /* 注销以后,设备就不存在了 */
printk("A Simple Device has been removed,Bye!\n").
}
/*
* 编译这个模块然后加载它,
* 如果正常,会显示你的设备的主设备号。
* 现在你的设备就建立好了,我们可以测试一下。
* 假设你的模块申请到的主设备号是254,
* 运行"mknod abc c 254 0",就建立了我们的设备文件abc。
* 可以把它当成一个4096字节的内存块来测试一下,
* 比如"cat abc", "cp abc image", "cp image abc",
* 或写几个应用程序用它来进行通讯。
* 介绍一下两个需要注意的事,
* 一是printk()的显示只有在非图形模式的终端下才能看到,
* 二是加载过的模块最好在不用以后卸载掉。
* 如果对Linux环境的系统调用很陌生,建议先看APUE这本书。
*/
static int
asdf_open /* open回调 */
(
struct inode *inode,
struct file *filp
){
printk("^_^ : open %s\n ",\
current->comm).
/*
* 应用程序的运行环境由内核提供,内核的运行环境由硬件提供。
* 这里的current是一个指向当前进程的指针,
* 现在没必要了解current的细节。
* 在这里,当前进程正打开这个设备,
* 返回0表示打开成功,内核会给它一个文件描述符。
* 这里的comm是当前进程在Shell下的command字符串。
*/