信号量机制

本文展示了一个简单的Linux字符设备驱动程序实现,包括模块初始化、文件操作和信号量使用等关键部分。通过信号量实现对缓冲区的安全访问,确保读写操作的原子性和互斥性。
#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);

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值