gpt4 book ai didi

c - getcontext 系统调用 (ucontext.h) 的真正作用是什么?

转载 作者:太空狗 更新时间:2023-10-29 16:49:29 28 4
gpt4 key购买 nike

我去年学习了操作系统,期间我使用用户上下文(在头文件 ucontext.h 中定义)为一个项目实现线程调度程序(其中每个线程模拟一个进程)。我正在参加一个讲座,将讨论用户上下文,我突然想到,尽管去年完成了这个项目,但我并不真正理解 getcontext 系统调用到底是什么确实如此。

man pages对于 getcontext 声明它

initializes the structure pointed at by ucp to the currently active context."

它还指出,对于 setcontext 的参数,如果 ucp 参数

was obtained by a call of getcontext(), program execution continues as if this call just returned.

好的,我明白了。

这就是我感到困惑的地方。通常,按照我的学习方式,要执行上下文切换,可以初始化 ucontext_t 结构并按如下方式交换/设置它:

ucontext_t ucp;
ucontext_t oucp;
getcontext(&ucp);

// Initialize the stack_t struct in the ucontext_t struct
ucp.uc_stack.ss_sp = malloc(STACK_SIZE);
ucp.uc_stack.ss_size = STACK_SIZE;
ucp.uc_stack.ss_flags = 0;

ucp.uc_link = /* some other context, or just NULL */;

// Don't block any signals in this context
sigemptyset(&ucp.uc_sigmask);
// Assume that fn is a function that takes 0 arguments and returns void
makecontext(&ucp, fn, 0);

// Perform the context switch. Function 'fn' will be active now
swapcontext(&oucp, &ucp);
// alternatively: setcontext(&ucp);

如果我在较小的程序中省略 getcontext,则不会发生任何有趣的事情。在通过用户上下文进行更多上下文切换的稍大一些的程序中,我遇到了一个段错误,只能通过重新添加 getcontext 来解决。

getcontext 究竟做了什么?为什么我不能只分配一个 ucontext_t 结构,通过初始化 uc_stackuc_sigmask 字段来初始化它,然后调用 makecontext 没有 getcontext?是否有一些 getcontext 执行而 makecontext 不执行的必要初始化?

最佳答案

我查看了 x86/linux 架构上 ucontext 的 GNU libc 实现,因此,可能存在以下不适用的不同实现。

GNU libc manual指出:

The ucp parameter passed to the makecontext shall be initialized by a call to getcontext.

如果你查看 glibc/sysdeps/unix/linux/x86/sys/ucontext.h 中的 mcontext_t,有一个指向浮点状态的指针 (fpregset_t fpregs),它在 getcontext() 中初始化并在 setcontext( ).但是,它不是使用 makecontext() 初始化的。我用 GDB 做了一个快速测试,在 setcontext() 中尝试取消引用指向未由 getcontext() 初始化的 ucontext_t 结构中的浮点上下文的指针时出现段错误:

=> 0x00007ffff784308c <+44>: fldenv (%rcx)

关于c - getcontext 系统调用 (ucontext.h) 的真正作用是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19503925/

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