用c语言写一个驱动程序示例
时间: 2023-05-18 16:02:48 浏览: 72
好的,以下是一个简单的C语言驱动程序示例:
#include <linux/module.h>
#include <linux/kernel.h>
#include <linux/init.h>
#include <linux/fs.h>
#include <linux/uaccess.h>
#define DEVICE_NAME "mydevice"
#define EXAMPLE_MSG "Hello, world!\n"
#define MSG_BUFFER_LEN 15
static int major;
static char msg_buffer[MSG_BUFFER_LEN];
static int msg_ptr;
static int device_open(struct inode *inode, struct file *file)
{
return 0;
}
static int device_release(struct inode *inode, struct file *file)
{
return 0;
}
static ssize_t device_read(struct file *filp, char *buffer, size_t length, loff_t *offset)
{
int bytes_read = 0;
if (*msg_buffer == 0)
return 0;
while (length && *msg_buffer) {
put_user(*(msg_buffer++), 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 = 0; i < length && msg_ptr < MSG_BUFFER_LEN; i++)
get_user(msg_buffer[msg_ptr++], buffer + i);
return i;
}
static struct file_operations fops = {
.owner = THIS_MODULE,
.read = device_read,
.write = device_write,
.open = device_open,
.release = device_release
};
static int __init mydevice_init(void)
{
major = register_chrdev(0, DEVICE_NAME, &fops);
if (major < 0) {
printk(KERN_ALERT "Failed to register character device\n");
return major;
}
printk(KERN_INFO "Registered character device with major number %d\n", major);
return 0;
}
static void __exit mydevice_exit(void)
{
unregister_chrdev(major, DEVICE_NAME);
printk(KERN_INFO "Unregistered character device\n");
}
module_init(mydevice_init);
module_exit(mydevice_exit);
MODULE_LICENSE("GPL");
MODULE_AUTHOR("Your Name");
MODULE_DESCRIPTION("A simple character device driver");