clone.c 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. /* -*- mode:c; c-file-style:"k&r"; c-basic-offset: 4; tab-width:4; indent-tabs-mode:nil; mode:auto-fill; fill-column:78; -*- */
  2. /* vim: set ts=4 sw=4 et tw=78 fo=cqt wm=0: */
  3. #define _GNU_SOURCE
  4. #include <malloc.h>
  5. #include <unistd.h>
  6. #include <sys/types.h>
  7. #include <sys/wait.h>
  8. #include <signal.h>
  9. #include <sched.h>
  10. #include <stdio.h>
  11. // 64kB stack
  12. #define FIBER_STACK 1024 * 64
  13. __thread int mypid = 0;
  14. int thread_function (void * argument)
  15. {
  16. mypid = getpid();
  17. int * ptr = (int *) argument;
  18. printf("in the child: pid (%016lx) = %d\n", (unsigned long) &mypid, mypid);
  19. printf("in the child: pid = %d\n", getpid());
  20. printf("child thread exiting\n");
  21. printf("argument passed %d\n", *ptr);
  22. return 0;
  23. }
  24. int main (int argc, const char ** argv)
  25. {
  26. void * stack;
  27. pid_t pid;
  28. int varx = 143;
  29. mypid = getpid();
  30. printf("in the parent: pid = %d\n", getpid());
  31. // Allocate the stack
  32. stack = malloc(FIBER_STACK);
  33. if (stack == 0) {
  34. perror("malloc: could not allocate stack");
  35. _exit(1);
  36. }
  37. printf("child_stack: %016lx-%016lx\n", (unsigned long) stack,
  38. (unsigned long) stack + FIBER_STACK);
  39. // Call the clone system call to create the child thread
  40. pid = clone(&thread_function, (void *) stack + FIBER_STACK,
  41. CLONE_FS | CLONE_FILES | CLONE_SIGHAND | CLONE_VM,
  42. &varx);
  43. printf("clone() returned %d\n", pid);
  44. if (pid == -1) {
  45. perror("clone");
  46. _exit(2);
  47. }
  48. // Wait for the child thread to exit
  49. pid = waitpid(pid, 0, 0);
  50. if (pid == -1) {
  51. perror("waitpid");
  52. _exit(3);
  53. }
  54. // Free the stack
  55. free(stack);
  56. printf("in the parent: pid (%016lx) = %d\n", (unsigned long) &mypid, mypid);
  57. printf("in the parent: pid = %d\n", getpid());
  58. return 0;
  59. }