第一个linux驱动_读写设备文件(1)

平台:ubuntu12.04操作系统

第一步建立编译文件:

@sudo su     //输入密码 进入root

#cd  /drivers   //进入要建立驱动的文件夹

#   mkdir hello  // 建立第一个驱动文件的文件夹

#cd hello    //进入hello目录

#gedit hello.c

#include <linux/module.h>
#include <linux/init.h>
#inlcude <linux/kernel.h>
#include <linux/fs.h>
#include <linux/miscdevice.h>
#include <asm/uaccess.h>

//linnux驱动的装载函数
static int __init hello_drive_init(void)
{
    printk("hello drive init");
    return 0;
}
//linux驱动的卸载函数
static void __exit hello_drive_exit(void)
{
    printk("hello drive  exit"); 
}
//注册装载函数
module_int(hello_drive_init);
//注册卸载函数
module_exit(hello_drive_exit);


#gedit Makefile

obj-m := hello.o

第二步编译生成驱动模块

#make - C /usr/src/linux-headers-3.13.0-86-generic M=/usr/../drivers/hello   //M为hello.c文件目录  linuxheader 为所使用的linux内核版本,可通过#uname -r来查看ubuntu所使用的linux内核版本

编译之后在hello目录下生成.o和.ko的文件。

#insmod hello.ko   //安装hello.ko

第三步查看执行结果

#dmesg   //察看文件信息,

文件信息的末尾会出现

hello drive init

#rmmod hello  //卸载hello

#dmesg    //再次察看设备信息

信息末尾会显示:

hello drive init

hello drive  exit

或者也可以执行下面的命令来查看设备文件

# cat /var/log/syslog | grep hello             //也可以看到上述的设备文件信息

第四步查看模块信息

# modinfo hello.ko   //查看驱动模块的信息

filename:       hello.ko

license:        Dual BSD/GPL

srcversion:     325C4884B0A566C4476CF7D

depends:        

vermagic:       3.13.0-86-generic SMP mod_unload modversions 

可以在hello.c文件的末尾增加如下信息

MODULE_AUTHOR("wayy");
MODULE_DESCRIPTION("my first driver module");

重新编译,再次察看

# modinfo hello.ko   //查看驱动模块的信息

filename:       hello.ko

description:    my first driver module

author:         wuguowei

license:        Dual BSD/GPL

srcversion:     4B73C0A815A7B768711397E

depends:        

vermagic:       3.13.0-86-generic SMP mod_unload modversions

可以看到新增代码的部分已经被显示了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值