理解kernel编程

Last Updated: 2023-03-06 08:04:10 Monday

-- TOC --

kernel编程其实并不高深莫测,只是在kernel环境下编程,需要理解的东西变多了,编程本身还是一样的。不要沉迷于编程本身,深入理解系统才能更好的编程!

  1. kernel module不是application,模块在init后就进入类似于事件等待的状态,等待module内的函数被一次次反复地并发地调用,直到unload出kernel。
  2. exit函数必须要将init申请的资源,小心地全部释放掉,否则这些资源会一直被占用(泄露),直到reboot。(App退出后,所有资源被OS收回,因此泄漏的风险相对较小)
  3. module不能使用libc,即内核太没有运行时库,只能使用kernel内部提供的接口。
  4. 如果module崩溃,轻则进程退出,重则整个系统完蛋。
  5. module在kernel space,app在user space。(现代CPU都支持多种执行模式,execution mode,比如Intel的x86 CPU有4个ring,ring0--ring3。kernel space对应最高权限的执行模式,而user space对应最低权限。这两个space的区别:(1)可执行的instruction不同,(2)memory mapping不同:user space里的app,运行在虚拟内容空间,stack几乎无限高,而kernel space就是真实物理内存,stack也很小,因此不要使用很占内存的automatic variable。app通过系统调用,system call,进入内核,system call的上小文总是某个process。中断也会进入内核,异步,但不与任何process相关)
  6. module提供的函数,被并发地调用!比如有多个process在同时使用module提供的接口,或者在SMP环境下,module同时在多个CPU上被调用。
  7. Kernel code cannot do floating point arithmetic. Enabling floating point would require that the kernel save and restore the floating point processor’s state on each entry to, and exit from, kernel space, at least, on some architectures. Given that there really is no need for floating point in kernel code, the extra overhead is not worthwhile.(Windows内核可以做float point计算)
  8. kernel就像一个框架,各种功能用module来填充!(有一种驱动,叫做用户态驱动)

kernel代码中sys_开头的函数,都是system call!

Linux kernel可以动态加载或卸载module,这个机制在开发的时候非常方便!Kernel在编译时,可以配置是否支持module的动态加载或卸载。

本文链接:https://cs.pynote.net/sf/linux/dd/202111276/

-- EOF --

-- MORE --