第一个字符设备驱动程序


驱动代码:

/*
 * test.c
 *
 *  Created on: 2016年10月29日
 *      Author: chy
 */

#include <linux/stat.h>
#include <linux/types.h>
#include <linux/unistd.h>
#include <linux/fcntl.h>
#include <linux/string.h>
#include <linux/init.h>
#include <linux/kernel.h>
#include <linux/fs.h>
#include <linux/device.h>
#include <linux/cdev.h>
#include <linux/module.h>

static struct class *test_class;
static struct class_device *test_device;

static int open_test(struct inode * Inode,struct file *file_test)
{
	printk(KERN_EMERG "open test_file\n");
	return 0;
}

static ssize_t write_test(struct file *open_file,const char __user *buf_user,size_t count,loff_t *off)
{
	printk(KERN_EMERG "write file\n");
	return 0;
}

static int close_file(struct inode *node,struct file *File)
{
	printk(KERN_EMERG "close file\n");
	return 0;
}

struct file_operations file_p= {
		.write = write_test,
		.release = close_file,
		.open = open_test,
};


struct cdev devss;
dev_t devs;

static int init_devc(void)
{
	printk(KERN_EMERG "加载模块\n");
	devss.owner = THIS_MODULE;
	cdev_init(&devss,&file_p);

	alloc_chrdev_region(&devs,0,1,"test_dev");
	cdev_add(&devss,devs,1);
	test_class = class_create(THIS_MODULE,"test");
	device_create(test_class,NULL,devs,NULL,"test_device");

	return 0;
}

static void exit_devc(void)
{
	printk(KERN_EMERG "卸载模块\n");
	cdev_del(&devss);
	unregister_chrdev_region(devs,1);
	device_destroy(test_class,devs);
	class_destroy(test_class);

	 return;
}

MODULE_LICENSE("GPL");
module_init(init_devc);
module_exit(exit_devc);


验证:

/*
 * test_ying_yong.c
 *
 *  Created on: 2016年11月2日
 *      Author: chy
 */

#include <sys/stat.h>
#include <sys/types.h>
#include <sys/unistd.h>
#include <sys/fcntl.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#define Max 256
#define ERR(msg,f) { \
	if(f < 0) {\
		fprintf(stderr,"%s",msg); \
		exit(-1); \
	} \
}

int main(int argc,char *argv[])
{
	int fid,write_num;
	char buffer[Max];

	fid = open("/dev/test_device",O_RDWR);
	ERR("open test_device failed\n",fid);

	write_num = write(fid,buffer,Max);
	ERR("write file failed\n",write_num);

	close(fid);
	return 0;
}




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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值