我刚开始研究系统调用。
我想知道进行系统调用时是什么导致了开销。
例如,
如果我们考虑 getpid(),当对 getpid() 进行系统调用时,我的猜测是,如果控件当前在子进程中,则必须进行上下文切换以进入父进程以获取 pid。这会导致开销吗?
同样在调用getpid()时,也会有一些元数据跨用户空间边界的传递,进出内核。那么用户空间和内核之间的不断切换是否也会造成一些开销呢?
最佳答案
For example, if we consider getpid(), when a system call is made to getpid() my guess is that if the control is currently in the child process then a context switching has to be made to enter the parent process to get the pid.
这里不需要切换到子进程——内核应该拥有所有可用的必要数据。在大多数情况下,内核只会在调度程序中或从系统调用返回时将上下文切换到用户空间进程。
Also when getpid() is called, there will be some metadata transfer across the user-space boundary and enters and exits the kernel. So will the constant switching between user space and kernel also cause some overhead?
是的,如果
getpid()
经常被调用,开销肯定会增加。有一些可用的方法可以避免简单的“getter”系统调用(如 getpid()
)的这种开销。和 gettimeofday()
;曾经在 Linux 下使用过的一种方法是将系统调用的(已知)结果存储在一个特殊的内存页面中。 (这种机制被称为 vsyscall 。)
关于process - 系统调用开销,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23599074/