Linux驱动程序开发的简单休眠

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;  /*成功并避免重试*/

}

 

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wyfgjs.html