c - ucontext.h and uc_link not returning from main thread -


here want part of larger thread scheduling api.

i want create thread , when main thread (the 1 creating thread) exits, thread created should execute. trying ucontext , uc_link, not working. appears uc_link not work when try set current thread.

here modified example link tired make work.

http://pubs.opengroup.org/onlinepubs/009695399/functions/makecontext.html

#include <stdio.h> #include <ucontext.h>   static ucontext_t ctx[3];   static void f1 (void) {     puts("start f1");     swapcontext(&ctx[1], &ctx[2]);     puts("finish f1"); }   static void f2 (void) {     puts("start f2");     swapcontext(&ctx[2], &ctx[1]);     puts("finish f2"); }   int main (void) {     char st1[8192];     char st2[8192];       getcontext(&ctx[1]);     ctx[1].uc_stack.ss_sp = st1;     ctx[1].uc_stack.ss_size = sizeof st1;     ctx[1].uc_link = 0;     makecontext(&ctx[1], f1, 0);       getcontext(&ctx[2]);     ctx[2].uc_stack.ss_sp = st2;     ctx[2].uc_stack.ss_size = sizeof st2;     ctx[2].uc_link = &ctx[1];     makecontext(&ctx[2], f2, 0);      getcontext(&ctx[0]);     ctx[0].uc_link = &ctx[2];     return 0; } 

expected output :

finished main start f2 start f1 finish f2 finish f1 

given output :

finished main 

how go setting uc_link current thread/process in meaningful manner ?

replacing main in above code following produces expected output.

int main (void) {     char st1[8192];     char st2[8192];      getcontext(&ctx[1]);     ctx[1].uc_stack.ss_sp = st1;     ctx[1].uc_stack.ss_size = sizeof st1;     ctx[1].uc_link = &ctx[0];     makecontext(&ctx[1], f1, 0);      getcontext(&ctx[2]);     ctx[2].uc_stack.ss_sp = st2;     ctx[2].uc_stack.ss_size = sizeof st2;     ctx[2].uc_link = &ctx[1];     makecontext(&ctx[2], f2, 0);      getcontext(&ctx[0]);     ctx[0].uc_mcontext.gregs[16] += 0x26;     puts("finish main");     setcontext(&ctx[2]);     return 0; } 

but doesn't want.

the context functions way put specific return address on stack.

  • getcontext captures address of next instruction struct
  • makecontext changes address in struct of function argument
  • setcontext/swapcontext puts address in struct on stack , returns it

this program above has 1 thread of control. think want multiple threads, in case wouldn't use these context functions.

for more information stack , c calling convention, eli bendersky has 2 nice articles diagrams:

fwiw, 0x26 constant in above code, had disassemble main find first address after setcontext call.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -