#include <linux/module.h>
#include <linux/init.h>
#include <linux/slab.h>
#include <linux/fs.h>
#include <linux/mm.h>
#include <linux/kernel.h>
#include <linux/cdev.h>
#include <linux/types.h>
#include <linux/semaphore.h>
#include <asm/uaccess.h>
#define LEN 3
struct cdev cdev;
dev_t devno;
int buff[LEN];
int r,w;
struct semaphore slots,data;
ssize_t hopen(struct inode *inode,struct file *file)
{
return 0;
}
int hrelease(struct inode *inode,struct file *file)
{
return 0;
}
ssize_t hread(struct file *file,const char __user *da,size_t n,loff_t fpos)
{
int x;
down(&data);
x = buff[r];
if(copy_to_user((void *)da,&x,sizeof(int)))
return -1;
buff[r] = -1;
r = (r+1)%LEN;
up(&slots);
return 0;
}
ssize_t hwrite(struct file *file,char __user *da,size_t n,loff_t fpos)
{
int y;
down(&slots);
if(copy_from_user(&y,da,sizeof(int)))
return -1;
buff[w] = w;
w = (w+1)%LEN;
up(&data);
return 0;
}
struct file_operations fops =
{
#if 1
.open = hopen,
.read = hread,
.write = hwrite,
.release = hrelease,
#endif
};
static int hello_init(void)
{
r = w = 0;
sema_init(&slots,LEN);
sema_init(&data,0);
alloc_chrdev_region(&devno,0,1,"sem");
cdev_init(&cdev,&fops);
cdev_add(&cdev,devno,1);
return 0;
}
static void hello_exit(void)
{
unregister_chrdev_region(devno,1);
cdev_del(&cdev);
}
MODULE_AUTHOR("xx");
MODULE_LICENSE("GPL");
module_init(hello_init);
module_exit(hello_exit);
信号量机制
最新推荐文章于 2025-02-10 17:42:15 发布
