linux 驅動學習之阻塞 I/O

來源:互聯網
上載者:User

為了將進程以一種安全的方式進入休眠,我們需要牢記兩條規則:
一、永遠不要在原子上下文中進入休眠。
二、進程休眠後,對環境一無所知。喚醒後,必須再次檢查以確保我們等待的條件真正為真

測試例子只是針對休眠的幾個函數,例子本身沒什麼意義。測試例子在讀的時候休眠直到條件滿足後喚醒,再寫的時候喚醒一個等待讀的進程如果有進程在讀的話。

static DECLARE_WAIT_QUEUE_HEAD(hwait);static unsigned state=0;ssize_t fileops_read(struct file *filp, char __user *buff, size_t count, loff_t *offp){   printk(KERN_ALERT "process %i (%s) wait for read\n",current->pid,current->comm);//  wait_event(hwait,state!=0);                                /*進程將被置於非中斷休眠*/       wait_event_interruptible(hwait,state!=0);                  /*進程可被訊號中斷休眠,返回非0值表示休眠被訊號中斷*//*等待限定時間jiffy,條件滿足返回0,過程不可訊號中斷*///  wait_event_timeout(hwait,state!=0,10 * HZ);                //不可中斷休眠等待10秒,逾時返回0,成功返回剩餘jiffies/*等待限定時間jiffy,條件滿足返回0,過程可被訊號中斷*///  wait_event_interruptible_timeout(hwait,state!=0,10*HZ);    //可中斷休眠等待10秒,逾時返回0,成功返回剩餘jiffies,被中斷返回-ERESTARTSYS  state=0;  printk(KERN_ALERT "process %i (%s) awke up\n",current->pid,current->comm);  return 0;}ssize_t fileops_write(struct file *filp, const char __user *buff, size_t count, loff_t *offp){  /*這裡系統調用會一直寫 直到寫夠count,如返回小於count的數,會再次調用此方法直到返回錯誤或寫夠count*/    printk(KERN_ALERT "process %i (%s) wake up all\n",current->pid,current->comm);  state=1;  wake_up_interruptible(&hwait);//注意不可中斷的休眠不可用這個函數 應使用wake_up  return count;}

測試結果

開啟多個終端並讀裝置[root@localhost ctest]# cat /dev/moduledev60 再開啟一個裝置往裡面寫資料[root@localhost ctest]# echo 111 > /dev/moduledev60 每寫一次都會有個終端的cat返回,當然這裡不會列印什麼資料。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.