内核设备文件创建
#include <linux/module.h>
#include <linux/init.h>
#include <linux/platform_device.h>
#include <linux/gpio.h>
#include <linux/delay.h>
#include <linux/regulator/consumer.h>
#include <sound/soc.h>
#include <sound/jack.h>
#define BUFSIZE 1024
static char mybuf[100]="123";
static char mytestbuf[BUFSIZE];
static ssize_t show_my_device(struct device *dev,
struct device_attribute *attr, char *buf)
{
return sprintf(buf, "%s\n", mybuf);
}
static ssize_t set_my_device(struct device *dev,
struct device_attribute *attr,
const char *buf, size_t len)
{
sprintf(mybuf, "%s", buf);
return len;
}
static DEVICE_ATTR(my_device_test, S_IWUSR|S_IRUSR, show_my_device, set_my_device);
static int mytest_device_open(struct inode *inode, struct file *filp)
{
return 0;
}
static int mytest_device_release(struct inode *inode, struct file *filp)
{
return 0;
}
ssize_t mytest_device_read(struct file *file, char __user *ubuf, size_t count, loff_t *ppos)
{
int size;
int ret;
if(*ppos > 0){
return 0;
}
size = strlen(mytestbuf);
if(copy_to_user(ubuf, mytestbuf, size)){
return -EFAULT;
}else{
*ppos = *ppos + size;
ret = size;
}
return ret;
}
static ssize_t mytest_device_write(struct file *file, const char __user *ubuf, size_t count, loff_t *ppos)
{
int size;
int i;
if(count <= 0){
return 0;
}
for(i = 0; i < BUFSIZE; i++){
mytestbuf[i]= '\0';
}
size = count > BUFSIZE-1 ? BUFSIZE-1 : count;
if(copy_from_user(mytestbuf, ubuf, size)){
return -EFAULT;
}
return size;
}
struct file_operations mytest_ops={
.owner = THIS_MODULE,
.open = mytest_device_open,
.release = mytest_device_release,
.read = mytest_device_read,
.write = mytest_device_write,
};
static int major;
static struct class *cls;
static int mytest_init(void)
{
struct device *mydev;
major=register_chrdev(0,"mytest", &mytest_ops);
cls=class_create(THIS_MODULE, "mytest_class");
mydev = device_create(cls, 0, MKDEV(major,0),NULL,"mytest_device");
if(sysfs_create_file(&(mydev->kobj), &dev_attr_my_device_test.attr)){
return -1;
}
return 0;
}
static void mytest_exit(void)
{
device_destroy(cls, MKDEV(major,0));
class_destroy(cls);
unregister_chrdev(major, "mytest");
}
module_init(mytest_init);
module_exit(mytest_exit);
MODULE_LICENSE("GPL");

浙公网安备 33010602011771号