Linux驱动 读写一个文件 代码
时间: 2023-03-30 15:02:26 浏览: 98
您好,以下是读写一个文件的 Linux 驱动代码示例:
#include <linux/fs.h>
#include <linux/init.h>
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "mydevice"
#define BUF_LEN 1024
MODULE_LICENSE("GPL");
static int major;
static char msg[BUF_LEN];
static char *msg_ptr;
static int device_open(struct inode *inode, struct file *file)
{
msg_ptr = msg;
try_module_get(THIS_MODULE);
return ;
}
static int device_release(struct inode *inode, struct file *file)
{
module_put(THIS_MODULE);
return ;
}
static ssize_t device_read(struct file *filp, char *buffer, size_t length, loff_t *offset)
{
int bytes_read = ;
if (*msg_ptr == )
return ;
while (length && *msg_ptr) {
put_user(*(msg_ptr++), buffer++);
length--;
bytes_read++;
}
return bytes_read;
}
static ssize_t device_write(struct file *filp, const char *buffer, size_t length, loff_t *offset)
{
int i;
for (i = ; i < length && i < BUF_LEN; i++)
get_user(msg[i], buffer + i);
msg_ptr = msg;
return i;
}
static struct file_operations fops = {
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release,
};
static int __init mydevice_init(void)
{
major = register_chrdev(, DEVICE_NAME, &fops);
if (major < ) {
printk(KERN_ALERT "Registering char device failed with %d\n", major);
return major;
}
printk(KERN_INFO "I was assigned major number %d. To talk to\n", major);
printk(KERN_INFO "the driver, create a dev file with\n");
printk(KERN_INFO "'mknod /dev/%s c %d '.\n", DEVICE_NAME, major);
return ;
}
static void __exit mydevice_exit(void)
{
unregister_chrdev(major, DEVICE_NAME);
printk(KERN_INFO "Goodbye, world!\n");
}
module_init(mydevice_init);
module_exit(mydevice_exit);
希望对您有所帮助。