Howarekernels(andoperatingsystemsingeneral)writteninC?
I'm trying to understand how you set about writing an OS in something like C.
I've always used C to write applications - using commands like malloc and fork and so on to request things from the OS. If these methods don't exist when you're programming the OS itself (or perhaps the Kernel in particular), how do you write them?
How do you implement memory and process management and so on, specifically what functions are available and what is exposed to allows you to do this in C instead of assembler? (what do you call to interact with memory / devices / interrupts?)
I can imagine this isn't a small question, so I'm more than happy for an answer that includes some further reading but if you'd be able to summarise the main points related to each question that would be super handy for me!
Thanks in advance!
EDIT (8/3/20):
这个相关的问题附有一些很好的资源,有助于回答这个问题:
操作系统开发入门有哪些资源?
回答
你如何实现内存
编写自己的分配器是一种常见的系统编程练习。“外部”唯一需要的是要管理的内存区域。如果您正在对裸机进行编程,您可能会有一个可用的内存映射来描述哪些区域是 RAM。这些你可以用 malloc 管理。
和流程管理
现代操作系统上的进程有很多东西。它们通常有自己的页表、上下文(在进程暂停时保存的寄存器)和许多其他特定于进程的数据结构。
您可以在 C 中设置的数据结构,但它们的“激活”(切换页表、保存/恢复上下文)通常超出了便携式 C 中可能的范围。对于那些您有汇编例程或一些与 C 代码交错的内联汇编.
等等,特别是哪些函数可用以及公开的内容允许您在 C 而不是汇编程序中执行此操作?
有托管和独立的 C 实现。如果您编写自己的操作系统,您通常处于独立的 C 环境中,并且没有标准库提供的函数可供您使用。您依靠自己的代码、编写汇编例程或使用编译器内在函数。
你叫什么来与记忆互动
您可以将整数转换为指针并操作指针对象。volatile允许您告诉编译器您绝对想按照写入的顺序进行读/写。
设备
许多设备是内存映射的,这意味着您可以像读取/写入内存一样进行通信(简化;缓存可能会使这变得有点棘手)。其他设备可通过专用 I/O 端口寻址。那些需要特殊指令,编译器具有内部函数,或者您需要在汇编中实现(您可以从 C 调用)。
中断?
像上面那样。启用/禁用中断等部分可能需要专用指令。设置中断处理程序可能只是将函数指针写入正确地址的问题。
我很高兴得到一个包含一些进一步阅读的答案,但如果您能够总结与每个问题相关的要点,那对我来说将非常方便!
我的建议是为自己准备一个 ARM Cortex-M 并开始使用它。评论中提到的 osdev 也是一个非常好的资源。
- @MysteriousWaffle Plase remember this is not a tutorial site. There are books about this sobject and it won't take less to give even the details. Actually even more, because these books are typically directed to people who already have advanced programming skills and know the implementation language(s) very well.
- That's the problem answering far too broad (aka "unfocussed") questions. This answer contains a lot of missconceptions and (potentially dangerous) wrong information. While it might result from trying to not write a book right here, it will misslead other readers. This is one major reason why OT questions should be closed and not answered. You have enough reps to help moderating this site. Please use this privilege.