I'm trying to run a simple application in Mac OS X 10.5.8 that uses ucontext system calls getcontext, makecontext and switchcontext. I know it works on Linux, but I haven't been able to run it in Mac OS X. The code is pretty simple, it just switches context from two functions:
#include <stdio.h>
#include <stdlib.h>
#include <sys/ucontext.h>
#include <string.h>
#include <errno.h>
#define FATAL(msg) \
do { \
fprintf(stderr,"%s:%d:%s: %s\n",__FILE__,__LINE__,msg,strerror(errno)); \
exit(-1); \
} while(0)
#define STACK_SIZE 4096
ucontext_t main_context, foo_context, bar_context;
char foo_stack[STACK_SIZE], bar_stack[STACK_SIZE];
void foo()
{
fprintf(stderr,"[foo] Starting\n");
fprintf(stderr,"[foo] Swap to bar_context\n");
if(swapcontext(&foo_context, &bar_context)<0)
FATAL("swapcontext\n");
fprintf(stderr,"[foo] Finishing\n");
}
void bar()
{
fprintf(stderr,"[bar] Starting\n");
fprintf(stderr,"[bar] Swap to foo_context\n");
if(swapcontext(&bar_context, &foo_context)<0)
FATAL("swapcontext\n");
fprintf(stderr,"[bar] Finishing\n");
}
int main(int argc, char *argv[])
{
/* Create context for foo() */
if(getcontext(&foo_context)<0)
FATAL("getcontext");
foo_context.uc_stack.ss_sp = foo_stack;
foo_context.uc_stack.ss_size = STACK_SIZE;
foo_context.uc_link = &main_context;
makecontext(&foo_context, foo, 0);
/* Create context for bar() */
if(getcontext(&bar_context)<0)
FATAL("getcontext");
bar_context.uc_stack.ss_sp = bar_stack;
bar_context.uc_stack.ss_size = STACK_SIZE;
bar_context.uc_link = (argc > 1) ? NULL : &foo_context;
makecontext(&bar_context, bar, 0);
fprintf(stderr,"[main] Swap to bar_context\n");
if(swapcontext(&main_context, &bar_context)<0)
FATAL("swapcontext");
fprintf(stderr,"[main] Finishing\n");
return(0);
}
I compile it using gcc context.c -o context, but the program only outputs "[main] Swap to bar_contex" forever, when it should switch context to the "foo" and "bar" functions, can someone give me a clue about what's happening?
Thanks, Roger Pau Monné.