為了將進程以一種安全的方式進入休眠,我們需要牢記兩條規則:
一、永遠不要在原子上下文中進入休眠。
二、進程休眠後,對環境一無所知。喚醒後,必須再次檢查以確保我們等待的條件真正為真
測試例子只是針對休眠的幾個函數,例子本身沒什麼意義。測試例子在讀的時候休眠直到條件滿足後喚醒,再寫的時候喚醒一個等待讀的進程如果有進程在讀的話。
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返回,當然這裡不會列印什麼資料。