Linux最簡單的休眠方式是wait_event(queue,condition)及其變種,在實現休眠的同時,它也檢查進程等待的條件。四種wait_event形式如下:
wait_event(queue,condition);/*不可中斷休眠,不推薦*/
wait_event_interruptible(queue,condition);/*推薦,返回非零值意味著休眠被中斷,且驅動應返回-ERESTARTSYS*/
wait_event_timeout(queue,condition,timeout);
wait_event_interruptible_timeout(queue,conditon,timeout);/*有限的時間的休眠,若超時,則不管條件為何值返回0*/
喚醒休眠進程的函數:wake_up
void wake_up(wait_queue_head_t *queue);
void wake_up_interruptible(wait_queue_head *queue);
慣例:用wake_up喚醒wait_event,用wake_up_interruptible喚醒wait_event_interruptible
休眠與喚醒 實例分析:
本例實現效果為:任何從該設備上讀取的進程均被置於休眠。只要某個進程向給設備寫入,所有休眠的進程就會被喚醒。
static DECLARE_WAIT_QUEUE_HEAD(wq);
static int flag =0;
ssize_t sleepy_read(struct file *filp,char __user *buf,size_t count,loff_t *pos)
{
pirntk(KERN_DEBUG "process %i (%s) going to sleep\n",current->pid,current->comm);
wait_event_interruptible(wq,flag!=0);
flag=0;
printk(KERN_DEBUG "awoken %i (%s) \n",current->pid,current->comm);
return 0;
}
ssize_t sleepy_write(struct file *filp,const char __user *buf,size_t count,loff_t *pos)
{
printk(KERN_DEBUG "process %i (%s) awakening the readers ...\n",current->pid,current->comm);
flag=1;
wake_up_interruptible(&wq);
return count; /*成功並避免重試*/
}