2011-05-14 202 views
8

在我的樣本Linux內核模塊之一,我有一個變量Device_Open聲明爲static的所有功能和功能device_open內聲明靜態變量counter之外。在device_open裏面,我增加了Device_Opencounter。該模塊沒有任何錯誤地插入內核,我爲我的模塊/ dev/chardev創建了一個設備文件。靜態全局變量和靜態局部變量

我做cat /dev/chardev。我能看到的是,counter每增加一個cat /dev/chardev,但是Device_Open總是保持爲0.與行爲差異相關的增量變量值的原因是什麼?

下面的代碼片段的理解

static int Device_Open = 0; 

static int device_open(struct inode *inode, struct file *file) 
{ 
    static int counter = 0; 

    printk(KERN_INFO "Device_Open = %d", Device_Open); 
    printk(KERN_INFO "counter = %d", counter); 

    if (Device_Open) 
     return -EBUSY; 

    Device_Open++; 
     counter++; 

    try_module_get(THIS_MODULE); 

    return SUCCESS; 
} 
+1

您確定在關閉設備(調用device_close()時)時不會遞減Device_Open嗎? – Antti 2011-05-14 09:44:25

+0

@感謝Antti ...我得到了缺失的鏈接。 – 2011-05-14 09:55:34

+0

在提問之前,請花更多時間閱讀您自己的代碼。 – moorray 2011-05-14 11:49:12

回答

7

我搜索「Device_open」,我發現它的相應的設備發佈。你確定你沒有這個功能嗎?我發現它在TLDP

static int device_release(struct inode *inode, struct file *file) 
{ 
#ifdef DEBUG 
    printk(KERN_INFO "device_release(%p,%p)\n", inode, file); 
#endif 

    /* 
    * We're now ready for our next caller 
    */ 
    Device_Open--; 

    module_put(THIS_MODULE); 
    return SUCCESS; 
} 
+5

+1閱讀海報的頭腦。 – 2011-05-14 09:48:05

+0

完美...我錯過了執行'cat/dev/chardev'後,/ dev/chardev設備文件關閉,內核inturn調用'device_release'來減少'Device_Open'的值。感謝您提醒我缺少的鏈接。 – 2011-05-14 09:54:41