免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 670 | 回复: 0
打印 上一主题 下一主题

字符设备学习实例 [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2008-04-12 18:24 |只看该作者 |倒序浏览
这是一个字符驱动的框架,使用固定分配主设备号和次设备号,功能只是读取内核
中的一段字符串“hello world!”但是麻雀随小无脏俱全!
模块代码
/*chardev.c*/
#include
#include  /*for file-f_op*/
#include
#include  /*for copy_to_user()*/
#include  /*for cdev ,cdev_init,cdev_add....*/
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Helight");
#define DP_MAJOR 250 /*the major number of the chardev*/
#define DP_MINOR 0 /*the minor number of the chardev*/
static int char_read(struct file *filp,char __user *buffer,size_t,loff_t
*); /*the read operation of the chardev----read the data from kernel*/
static int char_open(struct inode *,struct file *); /*open the chardev*/
static int char_write(struct file *filp,const char __user *buffer,size_t
,loff_t*); /*write data to kernel*/
static int char_release(struct inode *,struct file *); /*release the
chardev*/
static char *arr,*p;
static int chropen; /*the chardev open or not*/
struct cdev *chardev; /*define a char device*/
static int len;
struct file_operations char_ops = {
.read = char_read,
.write = char_write,
.open = char_open,
.release = char_release,
};
static int __init char_init(void)
{
dev_t dev;
printk(KERN_ALERT"Initing......\n");
dev=MKDEV(DP_MAJOR,DP_MINOR);
chardev = cdev_alloc( );
if(chardev==NULL){
return -1;
}
if(register_chrdev_region(dev,10,"chardev")ops = &char_ops;
cdev_init(chardev,&char_ops);
if(cdev_add(chardev,dev,1)
#include
#include
#include
#include
#include
#include
int main(void)
{
int testdev;
int i;
char buf[15];
testdev = open("/dev/chardev0",O_RDWR);
if ( testdev == -1 )
{
printf("Cann't open file \n");
exit(0);
}
memset(buf, 0, sizeof(buf));
if(i=read(testdev,buf,12)<0)
perror("read error\n");
printf("Re:%d %s\n",i,buf);
close(testdev);
return 0;
}
Makefile文件:
obj-m:=chardev.o
KERNELDIR=/usr/src/linux-headers-2.6.22-14-generic/
all:
$(MAKE) -C $(KERNELDIR) M=$(PWD) modules
gcc -o main main.c
使用步骤:
1。make模块
2。insmod模块
3。mknod结点,具体命令如下:
mknod /dev/chardev0 c 250 0
命令解释:
mknod是建立节点的命令;
/dev/chardev0:在/dev/目录下建立chardev0这样一个节点,
c:这个节点是指向一个字符设备的节点
250:这个设备的主设备号;
0:次设备号
4。chmod 666 /dev/chardev0 使其他用户也可以对这个设备进行读写操作,否则
只有root用户可以对他进行读写
5。编译用户程序
6,运行用户程序./main
7.如果没有什么问题的话应该要输出
Re:12 hello world!
这几个字符。
               
               
               

本文来自ChinaUnix博客,如果查看原文请点:http://blog.chinaunix.net/u2/65841/showart_528647.html
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP