驱动代码:
/*
* 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;
}