2011-05-14 204 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