2016-03-16 35 views
1

这是一个新手的内核模块的问题...我有mymodule.c的一个功能:Linux内核模块如何知道它的文件何时被打开?

static int mymodule_open(struct inode *inode, struct file *filp) 
{ 
    //printk(KERN_INFO "open called\n"); 
    /* Success */ 
    return 0; 
} 

和用户级程序,其中变量初始化后的第一行是:

FILE *pFile = fopen("/dev/mymodule", "r+"); 

当我运行用户级程序这fopen莫名其妙地调用mymodule.c的的mymodule_open命令(编译mymodule.ko)。它如何知道这样做?关于mymodule_open()如何知道当fopen打开/dev/mymodule时,我无法连接点。

+1

您联系'mymodule_open'以'file_operations'结构,对不对?从那里连接点... – nneonneo

+2

阅读非常好的[Linux设备驱动程序](http://shop.oreilly.com/product/9780596000080.do)。具体来说,请参阅[主要和次要数字]一节(http://www.xml.com/ldd/chapter/book/ch03.html#t2) – kaylum

+1

需要注意的事项:内核维护一个打开的“refcount “为每个设备。如果你做'xf1 = fopen(“/ dev/mymodule”,...); xf2 = fopen(“/ dev/mymodule”,...);'然后'fclose(xf2); fclose(xf1)',你的'mymodule_open'将只为'xf1'调用,'mymodule_close'只为'xf1'调用。也就是说,无论有多少嵌套打开完成,驱动程序只在第一个回调中获得一个回调,并且只在最后一次关闭时才接近关闭。 –

回答

2

有在内核中的模块登记机构,用于设备驱动程序或内核模块。

/dev/module将与您的模块链接。

该设备的操作和文件操作结构被映射在与设备文件。

struct file_operations fops = { 
open : my_module_open, 
release : my_module_release, 
ioctl : my_module_ioctl, 
}; 

设备文件将确定并打开与设备文件的主要和次要number.First帮助的模块,然后文件操作结构。

还应考虑device registrationdevice file operations

1

当下用户空间打的fopen调用,它就会被发送到打开“系统调用”,并从那里到相应/注册驾驶FOPS开通话通过识别主要:设备文件的次要号码

每个设备文件都有一个“主要:次要”元组属于一个特定的驱动程序,相应的fops结构将支持声明/定义的操作。

的fopen(的/ dev/MyModule的) - > library_function(打开,file_arguments) - > 系统调用(打开,file_arguments) - > filesystem_driver(inode的,开放的, more_arguments) - > filesystem_driver(主要:次要的,开放, more_arguments) - > fops_structure(开,more_arguments)

注:上面的名字都是从FOPEN到mymodule_open,除此之外,河道水流的解释,名字都没有绝对的函数名,即, library_function,systemcall,filesystem_driver ...

司机知道在/ dev/mymodule中打开文件,因为它是作为以上述方式所提到的,从的fopen一个触发事件,功能各级别开始触发函数调用的一个新的水平,直至达到mymodule_open的最终功能内部驱动