Linux driver顺序锁操作
具体说明就不说了,直接给出demo:
seq_lock.c
#include<linux/init.h> #include<linux/module.h> #include<linux/kernel.h> #include<linux/fs.h> #include<asm/atomic.h> #include<linux/delay.h> #include<linux/random.h> #include<asm/uaccess.h> #include<linux/miscdevice.h> #define DEVICE_NAME "seq_lock" static DEFINE_SEQLOCK(seqlock); static ssize_t demo_read(struct file *file,char __user *buf,size_t count,loff_t *ppos){ unsigned seq; do{ seq=read_seqbegin(&seqlock); mdelay(10000); }while(read_seqretry(&seqlock,seq)); return 0; } static ssize_t demo_write(struct file *file,const char __user *buf,size_t count,loff_t *ppos){ struct timeval tv; do_gettimeofday(&tv); printk("write:start sec :%ld\n",tv.tv_sec); write_seqlock(&seqlock); do_gettimeofday(&tv); printk("write:end sec:%ld\n",tv.tv_sec); write_sequnlock(&seqlock); return count; } static struct file_operations dev_fops={ .owner=THIS_MODULE, .read=demo_read, .write=demo_write }; static struct miscdevice misc={ .minor=MISC_DYNAMIC_MINOR, .name=DEVICE_NAME, .fops=&dev_fops }; static int __init demo_init(void){ int ret=misc_register(&misc); printk("demo_init_success\n"); return ret; } static void __exit demo_exit(void){ printk("demo_exit_success\n"); misc_deregister(&misc); } module_init(demo_init); module_exit(demo_exit); MODULE_LICENSE("GPL"); MODULE_AUTHOR("zhibao.liu");
Makefile:
obj-m:=seq_lock.o
build.sh:
#!bash/bin make -C /usr/src/linux-headers-3.8.0-29-generic M=/root/workspace/drivers/seqrockmodule/
run.sh
#!bash/bin insmod seq_lock.ko lsmod | grep seq_lock dmesg | grep seq_lock | tail -n 2 modinfo seq_lock.ko rmmod seq_lock
顺序锁是写优先级高于读优先级,所以:
先打开一个终端:
cat /dev/seq_lock
然后立刻再打开一个终端:
echo "H" > /dev/seq_lock
会发现写操作会立刻执行,而读操作虽然首先开始执行,但是会发现读操作被阻塞了.

浙公网安备 33010602011771号