驱动程序的代码如下:
代码: 全选
#include <linux/init.h>
#include <linux/modules.h>
#include <linux/types.h>
#include <linux/fs.h>
#include <linux/cdev.h>
#define DEV_MAJOR 200
#define DEV_MINOR 0
char *buf = "abcdefghijklmnopqrstuvwxyz";
static int scull_open(struct inode *scull_inode,
struct file *scull_file);
static int scull_release(struct inode *scull_inode,
struct file*scull_file);
static ssize_t scull_read(struct file* fp, char *ubuf,
size_t count, loff_t *ppos);
dev_t scull_dev;
struct cdev *scull_cdev;
struct file_operations scull_fops =
{
.owner = THIS_MODULE,
.read = scull_read,
.open = scull_open,
.release = scull_release,
};
static int scull_open(struct inode *scull_inode,
struct file *scull_file)
{
return 0;
}
static int scull_release(struct inode *scull_inode,
struct file*scull_file)
{
return 0;
}
static ssize_t scull_read(struct file* fp, char *ubuf,
size_t count, loff_t *ppos)
{
int rc;
rc = copy_to_user(ubuf, buf, count);
return rc;
}
static int scull_init(void)
{
scull_dev = MKDEV(DEV_MAJOR, DEV_MINOR);
register_chrdev_region(scull_dev, 1, "scull");
scull_cdev = cdev_alloc();
scull_cdev->owner = THIS_MODULE;
scull_cdev->ops = &scull_fops;
cdev_init(scull_cdev, &scull_fops);
cdev_add(scull_cdev, scull_dev, 1);
return 0;
}
static void scull_exit(void)
{
cdev_del(scull_cdev);
unregister_chrdev_region(scull_dev, 1);
}
module_init(scull_init);
module_exit(scull_exit);
测试代码如下:
#include <linux/fs.h>
#include <stdio.h>
int main()
{
char buffer[64];
int count;
int fd;
fd = open("/dev/scull", 0);
read(fd, buffer, 20);
printf("%s", buffer);
close(fd);
return 0;
}