阻塞式i/o
如果無法立即滿足請(qǐng)求锚扎,一個(gè)驅(qū)動(dòng)程序應(yīng)該如何響應(yīng):
比如一個(gè)進(jìn)程嘗試寫瓶逃,但是你的設(shè)備沒有準(zhǔn)備好接受數(shù)據(jù),因?yàn)槟愕木彌_區(qū)是滿的炭分。調(diào)用過程通常不關(guān)心這些問題;程序員只是希望在必要的工作之后剑肯,呼叫讀寫捧毛,并有呼叫返回完成.因此,在這種情況下让网,你的驅(qū)動(dòng)程序應(yīng)該(默認(rèn))阻止進(jìn)程呀忧,讓它睡眠,直到請(qǐng)求可以繼續(xù)溃睹。
睡眠
什么是睡眠:
當(dāng)一個(gè)進(jìn)程所請(qǐng)求的資源或操作無法立即完成而账,該進(jìn)程的狀態(tài)會(huì)被改變,它被放入阻塞隊(duì)列知道有相應(yīng)的事件發(fā)生因篇,它才會(huì)被喚醒泞辐。
睡眠的規(guī)矩
1、如果線程A持有鎖惜犀,比如自旋鎖铛碑,那A一定不能睡眠
2狠裹、一定要記得虽界,當(dāng)線程A被喚醒的時(shí)候,A不知道這段時(shí)間發(fā)生了什么涛菠,任何假設(shè)都是不成立的莉御。
3撇吞、當(dāng)然還有一點(diǎn)線程A睡眠前,一定要確保有另一個(gè)線程B一定會(huì)把A叫醒礁叔。
如何找到睡眠的進(jìn)程
當(dāng)進(jìn)程睡眠的時(shí)候它會(huì)到等待隊(duì)列中注冊(cè)牍颈,負(fù)責(zé)叫醒的線程只要到該等待隊(duì)列中把所有睡眠的線程叫醒就行了。
等待隊(duì)列被定義在<linux/wait.h>中琅关。
一般的等待隊(duì)列是這樣聲明和初始化的:
wait_queue_head_t my_queue;
init_waitqueue_head(&my_queue);
Sleeping API
wait_event(queue , condition);
wait_event_interruptible(queue , condition);
wait_event_timeout(queue , condition , timeout);
wait_event_interruptible_timeout(queue , condition , timeout);
void wake_up(wait_queue_head_t *queue);
void wake_up_interruptible(wait_queue_head_t *queue);
如何實(shí)現(xiàn)一個(gè)阻塞式的i/o如管道:
ssize_t scull_read(struct file *filp , char __user *buf, size_t count,loff_t *f_pos)
{
if (down_interruptible(&mutex))
return -ERESTARTSYS;
ssize_t retval = 0;
while (size == 0) {
up(&mutex);
if (wait_event_interruptible(inq, (size != 0)))
return -ERESTARTSYS; /* signal: tell the fs layer to
handle it */
if (down_interruptible(&mutex))
return -ERESTARTSYS;
}
if (count > size)
count = size;
if (outp + count > MAX_SIZE){
if (copy_to_user(buf, store + outp, MAX_SIZE - outp)) {
retval = -EFAULT;
goto out;
}
if (copy_to_user(buf+ MAX_SIZE - outp, store, count + outp-MAX_SIZE)) {
retval = -EFAULT;
goto out;
}
}else{
if (copy_to_user(buf, store + outp , count)) {
retval = -EFAULT;
goto out;
}}
outp += count;
outp = (outp + count) % MAX_SIZE;
retval = count;
size -= count;
out:
up(&mutex);
wake_up_interruptible(&outq);
return retval;
}
ssize_t scull_write(struct file *filp , char __user *buf, size_t count,loff_t *f_pos)
{
if (down_interruptible(&mutex))
return -ERESTARTSYS;
ssize_t retval = 0;
while (size == MAX_SIZE) {
up(&mutex);
if (wait_event_interruptible(outq, (size != MAX_SIZE)))
return -ERESTARTSYS; /* signal: tell the fs layer tohandle it */
if (down_interruptible(&mutex))
return -ERESTARTSYS;
}
if (count > MAX_SIZE - size)
count =MAX_SIZE - size;
if (outp + count +size > MAX_SIZE){
if (copy_from_user(store + outp+size , buf, MAX_SIZE - outp - size)) {
retval = -EFAULT;
goto out;
}
if (copy_from_user(store, buf+MAX_SIZE - outp - size, count+outp + size-MAX_SIZE)) {
retval = -EFAULT;
goto out;
}
}else{
if (copy_from_user(store + outp +size , buf, MAX_SIZE - outp - size)) {
retval = -EFAULT;
goto out;
}}
size+= count;
retval = count;
out:
up(&mutex);
wake_up_interruptible(&inq);
return retval;
}
其他部分請(qǐng)參考:Linux內(nèi)核--簡(jiǎn)單的字符設(shè)備scull