Skip to content

Instantly share code, notes, and snippets.

@DanGe42
Created October 25, 2013 03:12
Show Gist options
  • Save DanGe42/7148938 to your computer and use it in GitHub Desktop.
Save DanGe42/7148938 to your computer and use it in GitHub Desktop.
#include <ucontext.h>
#include <sys/types.h>
#include <signal.h>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define STACKSIZE 4096
void f(){
printf("Hello World\n");
}
int main(int argc, char * argv[]){
ucontext_t uc; // Context for function `f`
ucontext_t muc; // Context for `main` function
void * stack;
getcontext(&uc);
// This line isn't actually necessary. Can you figure out why?
getcontext(&muc);
stack = malloc(STACKSIZE);
uc.uc_stack.ss_sp = stack;
uc.uc_stack.ss_size = STACKSIZE;
uc.uc_stack.ss_flags = 0;
// Go back to the main context after the f context finishes
uc.uc_link = &muc;
sigemptyset(&(uc.uc_sigmask));
makecontext(&uc, f, 0);
while (1){
swapcontext(&muc,&uc);
printf("Hello Main\n");
// !!!
makecontext(&uc, f, 0);
}
//perror("setcontext"); //setcontext() doesn't return on success
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment