Created
October 23, 2013 23:56
-
-
Save DanGe42/7128935 to your computer and use it in GitHub Desktop.
The "hello world" user context example I demonstrated in class on Tuesday. The diff file attached shows one way you could modify it so that the program context switches back to `main` after `f` finishes.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| --- context_hello_world.c 2013-10-23 19:47:07.000000000 -0400 | |
| +++ context_hello_world1.c 2013-10-23 19:47:13.000000000 -0400 | |
| @@ -7,8 +7,11 @@ | |
| #define STACKSIZE 4096 | |
| +ucontext_t main_context; | |
| + | |
| void f(){ | |
| printf("Hello World\n"); | |
| + setcontext(&main_context); | |
| } | |
| int main(int argc, char * argv[]){ | |
| @@ -40,7 +43,7 @@ | |
| makecontext(&uc, f, 0); | |
| // context switch! | |
| - setcontext(&uc); | |
| + swapcontext(&main_context, &uc); | |
| perror("setcontext"); //setcontext() doesn't return on success | |
| return 0; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #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[]){ | |
| // some initialization | |
| ucontext_t uc; | |
| void * stack; | |
| // initialize the ucontext uc | |
| getcontext(&uc); | |
| // allocate some stack space | |
| stack = malloc(STACKSIZE); | |
| // uc_stack is just a struct that holds information about a stack, | |
| // specifically where it is in the heap (i.e. base pointer) and how big it is | |
| uc.uc_stack.ss_sp = stack; | |
| uc.uc_stack.ss_size = STACKSIZE; | |
| uc.uc_stack.ss_flags = 0; | |
| // we're not blocking any signals in the uc context | |
| sigemptyset(&(uc.uc_sigmask)); | |
| // when uc terminates, don't switch to another context (i.e. exit the program) | |
| // i.e. successor context | |
| uc.uc_link = NULL; | |
| // modifies the uc context to call the `(void)(*f)` function with no arguments | |
| makecontext(&uc, f, 0); | |
| // context switch! | |
| setcontext(&uc); | |
| 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