gpt4 book ai didi

linux - 为什么在内核开发中不能使用C标准库函数?

转载 作者:IT王子 更新时间:2023-10-28 23:59:09 34 4
gpt4 key购买 nike

刚开始学习内核开发,有一个小小的疑惑。为什么我们不能在内核开发中将它与c 库链接后使用c 函数?为什么内核从未与 c 库链接,而是有自己的一些标准 c 函数的实现,例如 printk() 而不是 printf()。如果内核是用 c 编写的,并在 c 编译器的帮助下编译,那么为什么我们不能使用 c 库中的标准函数?

最佳答案

因为你所熟悉的 GNU C 库是为用户模式而不是内核模式实现的。内核无法访问用户空间 API(这可能会调用对 Linux 内核的系统调用)。

来自KernelNewbies FAQ

Can I use library functions in the kernel ?

System libraries (such as glibc, libreadline, libproplist, whatever) that are typically available to userspace programmers are unavailable to kernel programmers. When a process is being loaded the loader will automatically load any dependent libraries into the address space of the process. None of this mechanism is available to kernel programmers: forget about ISO C libraries, the only things available is what is already implemented (and exported) in the kernel and what you can implement yourself.

Note that it is possible to "convert" libraries to work in the kernel; however, they won't fit well, the process is tedious and error-prone, and there might be significant problems with stack handling (the kernel is limited to a small amount of stack space, while userspace programs don't have this limitation) causing random memory corruption.

Many of the commonly requested functions have already been implemented in the kernel, sometimes in "lightweight" versions that aren't as featureful as their userland counterparts. Be sure to grep the headers for any functions you might be able to use before writing your own version from scratch. Some of the most commonly used ones are in include/linux/string.h.

Whenever you feel you need a library function, you should consider your design, and ask yourself if you could move some or all the code into user-space instead.

如果您需要使用标准库中的函数,您必须重新实现该功能,原因很简单 - 没有标准 C 库。

C 库基本上是在 Linux 内核(或其他操作系统的内核)之上实现的。

例如,C 库的 mkdir(3) 函数基本上只不过是 Linux 内核的系统调用 mkdir(2) 的包装。

http://linux.die.net/man/3/mkdir http://linux.die.net/man/2/mkdir

关于linux - 为什么在内核开发中不能使用C标准库函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13485271/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com