驱动程序函数中的静态全局变量和静态局部变量
在我的一个示例 Linux 内核模块中,我有一个在所有函数外部声明为静态的变量 Device_Open
和在函数 device_open
内部声明的静态变量 counter
。在 device_open
内部,我增加了 Device_Open
和 counter
。该模块插入内核时没有任何错误,并且我为模块 /dev/chardev 创建了一个设备文件。
我执行cat /dev/chardev
。我可以看到的是,每次调用 cat /dev/chardev
时,counter
都会增加,但 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;
}
In one of my sample Linux kernel module, I have a variable Device_Open
declared static outside all functions and a static variable counter
declared inside a function device_open
. Inside device_open
, i increment both Device_Open
and counter
. The module is inserted without any errors into the kernel and i created a device file for my module /dev/chardev.
I do cat /dev/chardev
. What i can see is that counter
gets incremented for each invocation of cat /dev/chardev
, but Device_Open
always remains 0. What is the reason for the difference in behavior related to incrementing the value of the variables ?
Below is the code snippet for understanding
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我搜索“Device_open”,找到了其对应的设备版本。你确定没有这个功能吗?我在 TLDP 找到了它。
I searched for "Device_open" and I found its corresponding device release. Are you sure you don't have this function ? I found it at TLDP.