ucontext implementation featuring glibc-compatible ABI

test_libucontext.c 965B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. /*
  2. * libucontext test program based on POSIX example program.
  3. * Public domain.
  4. */
  5. #include <stdio.h>
  6. #include <ucontext.h>
  7. #include <stdint.h>
  8. #include <string.h>
  9. static ucontext_t ctx[3];
  10. static void f1 (void) {
  11. printf("start f1\n");
  12. swapcontext(&ctx[1], &ctx[2]);
  13. printf("finish f1\n");
  14. }
  15. static void f2 (void) {
  16. printf("start f2\n");
  17. swapcontext(&ctx[2], &ctx[1]);
  18. printf("finish f2\n");
  19. }
  20. int main (int argc, const char *argv[]) {
  21. char st1[8192];
  22. char st2[8192];
  23. /* poison each coroutine's stack memory for debugging purposes */
  24. memset(st1, 'A', sizeof st1);
  25. memset(st2, 'B', sizeof st2);
  26. getcontext(&ctx[1]);
  27. ctx[1].uc_stack.ss_sp = st1;
  28. ctx[1].uc_stack.ss_size = sizeof st1;
  29. ctx[1].uc_link = &ctx[0];
  30. makecontext(&ctx[1], f1, 0);
  31. getcontext(&ctx[2]);
  32. ctx[2].uc_stack.ss_sp = st2;
  33. ctx[2].uc_stack.ss_size = sizeof st2;
  34. ctx[2].uc_link = &ctx[1];
  35. makecontext(&ctx[2], f2, 0);
  36. swapcontext(&ctx[0], &ctx[2]);
  37. return 0;
  38. }