使用结构体设置函数
在编写内核模块/驱动程序时,大多数时候会初始化一些结构以指向某些特定函数。作为这方面的初学者,有人可以解释一下这一点的重要性。
我在编写字符设备驱动程序时看到了 struct file_operations
我还发现,尽管声明了这些函数,但它们并不总是被实现。任何人都可以帮忙吗?例如,在内核源代码:kernel/dma.c中,尽管
static const struct file_operations proc_dma_operations = {
.open = proc_dma_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
定义了,但仅实现了proc_dma_open。
While writing kernel modules/drivers, most of the time some structures are initialized to point to some specific functions. As a beginner in this could someone explain the importance of this.
I saw the struct file_operations
while writing the character device driver
Also I found that eventhough the functions are declared they are not implemented always. Could anyone help on that too. For example, in the kernel source: kernel/dma.c, eventhough
static const struct file_operations proc_dma_operations = {
.open = proc_dma_open,
.read = seq_read,
.llseek = seq_lseek,
.release = single_release,
};
are defined, only proc_dma_open is implemented.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
函数
seq_read
、seq_lseek
和single_release
在内核源文件linux-3.1.6/include/linux/seq_file中声明。 h
并在内核源文件linux-3.1.6/fs/seq_file.c
中定义。它们可能是许多文件操作所共有的。The functions
seq_read
,seq_lseek
andsingle_release
are declared in the kernel source filelinux-3.1.6/include/linux/seq_file.h
and defined in the kernel source filelinux-3.1.6/fs/seq_file.c
. They are probably common to many file operations.如果您曾经使用过 C++ 等面向对象语言,请将 file_operations 视为基类,并将您的函数视为其虚拟方法的实现。
If you ever played with object-oriented languages like C++, think of
file_operations
as a base class, and your functions as being implementations of its virtual methods.函数指针是 C 语言中非常强大的工具,可以实时重定向函数调用。大多数(如果不是全部)操作系统都有类似的机制,例如旧的 MS-DOS 中臭名昭著的 INT 21 函数 25/35 允许 TSR 程序存在。
在 C 中,您可以将指向函数的指针分配给变量,然后通过该变量调用该函数。该函数可以在初始化时根据某些参数进行更改,也可以在运行时根据某些行为进行更改。
这是一个示例:
当指针“存在”在可以传递给系统调用的结构中时,这是一个非常强大的功能,允许挂钩到系统函数。
在面向对象语言中,可以通过使用反射动态实例化类来实现相同类型的行为。
Pointers to functions are a very powerful tool in the C language that allows for real-time redirect of function calls. Most if not all operating systems have a similar mechanism, like for example the infamous INT 21 functions 25/35 in the old MS-DOS that allowed TSR programs to exist.
In C, you can assign the pointer to a function to a variable and then call that function through that variable. The function can be changed either at init time based on some parameters or at runtime based on some behavior.
Here is an example:
When the pointer "lives" in a structure that can be passed to system calls, this is a very powerful feature that allows hooks into system functions.
In object oriented languages, the same kind of behavior can be achieved by using reflection to instantiate classes dynamically.