gpt4 book ai didi

c - 在 Mac OS mavericks 上运行 C 代码会产生无限循环,但在 Linux Ubuntu 上运行良好

转载 作者:太空宇宙 更新时间:2023-11-04 01:29:14 24 4
gpt4 key购买 nike

下面的代码在 ubuntu gcc 上运行良好,但在 mac OS mavericks 上进入无限循环。在两者上都使用 gcc48。它用于操作系统分配,因此我必须使用上下文并且不能使用 POSIX。当我在 MAC 上运行它时,它无限期地运行“打印”

#define _XOPEN_SOURCE 6000
#include <stdio.h>
#include <stdlib.h>
#include <ucontext.h>

void callback()
{
printf("callback start\n");
}

int main(void) {
ucontext_t ctx;
getcontext(&ctx);
ctx.uc_stack.ss_sp = malloc( sizeof(char) * 8192 );
ctx.uc_stack.ss_size = 8192;
ctx.uc_link = NULL;
printf("Print\n");
makecontext(&ctx, callback, 0);
setcontext(&ctx);
return 0;
}

最佳答案

来 self 对 setcontext(3) 的阅读,它应该是一个无限循环。调用 getcontext 初始化上下文。以下对 makecontext 的调用配置了 ctx,以便它在激活时调用 callback。对 setcontext 的最终调用如下

A successful call to setcontext() shall not return; program execution resumes at the point specified by the ucp argument passed to setcontext().

这意味着它将调用回调。当 callback 返回时

program execution continues as if the corresponding call of getcontext() had just returned

这会导致新的堆栈分配,然后调用 makecontextsetcontext

Apple manual page甚至更清楚并解决了这个确切的情况。

The setcontext() function makes a previously saved thread context the current thread context, i.e., the current context is lost and setcontext() does not return. Instead, execution continues in the con-text context text specified by ucp, which must have been previously initialized by a call to getcontext(), makecontext(3), or by being passed as an argument to a signal handler (see sigaction(2)).

If ucp was initialized by getcontext(), then execution continues as if the original getcontext() call had just returned (again).

我绝对同意@user3386109 和@JonathanLeffler 的评论——使用 POSIX 线程。

关于c - 在 Mac OS mavericks 上运行 C 代码会产生无限循环,但在 Linux Ubuntu 上运行良好,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25819228/

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