本文介绍了内核栈和用户栈有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在同一个程序中使用两个不同的堆栈有什么需要?Trap 如何将当前程序栈从用户栈变为内核栈?完成系统调用后如何返回用户栈?

What is the need of using two different stacks in same program? How does trap change the current stack of program from user stack to kernel stack? How does it come back to user stack after completing system call?

每个进程都有内核和用户栈吗?

Does every process have a kernel and user stack?

推荐答案

(基本上)有一个内核栈".每个 CPU.存在一个用户堆栈".对于每个进程,尽管每个线程都有自己的堆栈,包括用户线程和内核线程.

There is (basically) one "kernel stack" per CPU. There is one "user stack" for each process, though each thread has its own stack, including both user and kernel threads.

陷阱如何改变堆栈"其实很简单.

How "trapping changes the stack" is actually fairly simple.

CPU 因中断而改变进程或模式".中断的发生可能有很多不同的原因 - 发生故障(如错误或页面错误),或物理硬件中断(如来自设备) - 或定时器中断(例如,当进程使用所有这些都是分配的 CPU 时间").

The CPU changes processes or "modes", as a result of an interrupt. The interrupt can occur for many different reasons - a fault occurs, (like an error, or page-fault), or a physical hardware interrupt (like from a device) - or a timer interrupt (which occurs for example when a process has used all of it's allotted CPU time").

无论哪种方式 - 当调用此中断时,CPU 寄存器都保存在堆栈中 - 所有寄存器 - 包括堆栈指针本身.

Either way - when this interrupt is called, the CPU registers are saved on the stack - all the registers - including the stack pointer itself.

通常是一个调度程序";会被调用.然后调度程序选择另一个进程运行 - 恢复其所有保存的寄存器包括堆栈指针,并从它停止的地方继续执行(存储在返回地址指针中).

Typically then a "scheduler" would be called. The scheduler then chooses another process to be run - restoring all of its saved registers including the stack pointer, and continues execution from where it left off (stored in the return-address pointer).

这称为上下文切换".

我正在简化一些事情——比如如何保存和恢复内存管理上下文,但这就是我的想法.它只是为了响应中断而保存和恢复寄存器——包括堆栈指针".注册.

I'm simplifying a few things - like how memory management context are saved and restored, but that's the idea. It's just saving and restoring registers in response to an interrupt - including the "stack pointer" register.

所以每个程序或线程都有自己的(用户模式")堆栈(即多线程程序将有多个堆栈) - 以及上下文切换在这些之间切换.

So each program or thread has it's own ("user mode") stack (i.e. a multi-threaded program would have multiple stacks) - and the context switch switches between these.

更具体地说,内核模式";当机器(或特定 CPU)在内核中运行时存在堆栈.确切的处理是特定于操作系统的——例如,Linux 将每个 CPU 有一个中断(内核)堆栈(通常用于中断,包括页面错误和系统调用,它本质上包括几乎所有东西——比如设备驱动程序和调度程序).与用户空间线程一样,Linux 内核也有单独的内核线程堆栈.(Windows 内核做了一些不同的事情).

More specially, "Kernel Mode" stacks exist for when the machine (or a specific CPU) is running in the kernel. The exact handing is a OS specific - for example Linux will have one interrupt (kernel) stack per CPU (which would be generally used for interrupts, including page-faults and syscalls, which inherently includes nearly everything - like device drivers and the scheduler). Like user-space threads, Linux kernel also has separate stacks for kernel threads. (Windows Kernel does something different).

这篇关于内核栈和用户栈有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-20 06:57