a.定义信号量 struct semaphore sem;
b.初始化信号量 void sema_init(struct semaphore *sem, int val);
c.获得信号量P int down(struct semaphore *sem);//深度睡眠
int down_interruptible(struct semaphore *sem);//浅度睡眠
d.释放信号量V void up(struct semaphore *sem);
#include <linux/semaphore.h>
适用场合:任务上下文之间且临界区执行时间较长时的互斥或同步问题
mychar_sema.c
#include <linux/module.h> #include <linux/kernel.h> #include <linux/fs.h> #include <linux/cdev.h> #include <linux/wait.h> #include <linux/sched.h> #include <linux/poll.h> #include <asm/uaccess.h> #include "mychar.h" #define BUF_LEN 100 int major = 11; int minor = 0; int mychar_num = 1; struct mychar_dev { struct cdev mydev; char mydev_buf[BUF_LEN]; int curlen; struct semaphore sem; wait_queue_head_t rq; wait_queue_head_t wq;