Fork.c 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  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. /* This Hello World simply print out "Hello World" */
  4. #include "pal.h"
  5. #include "pal_debug.h"
  6. struct stack_frame {
  7. struct stack_frame* next;
  8. void* ret;
  9. };
  10. PAL_HANDLE _fork (void * args)
  11. {
  12. register struct stack_frame * fp __asm__ ("ebp");
  13. struct stack_frame * frame = fp;
  14. if (args == NULL) {
  15. struct stack_frame cur_frame = *frame;
  16. pal_printf("return address is %p\n", cur_frame.ret);
  17. return DkThreadCreate(&_fork, &cur_frame);
  18. }
  19. else {
  20. struct stack_frame * las_frame = (struct stack_frame *) args;
  21. pal_printf("(in child) return address is %p\n", las_frame->ret);
  22. return NULL;
  23. }
  24. }
  25. int main (int argc, char ** argv)
  26. {
  27. pal_printf("Enter Main Thread\n");
  28. PAL_HANDLE out = DkStreamOpen("dev:tty", PAL_ACCESS_WRONLY, 0, 0, 0);
  29. if (out == NULL) {
  30. pal_printf("DkStreamOpen failed\n");
  31. return -1;
  32. }
  33. void * param = NULL;
  34. PAL_HANDLE child = _fork(param);
  35. if (child == NULL) {
  36. pal_printf("in the child\n");
  37. char *str = (void *) DkVirtualMemoryAlloc(NULL, 20, 0,
  38. PAL_PROT_READ|PAL_PROT_WRITE);
  39. if (str == NULL) {
  40. pal_printf("DkVirtualMemoryAlloc failed\n");
  41. return -1;
  42. }
  43. str[0] = 'H';
  44. str[1] = 'e';
  45. str[2] = 'l';
  46. str[3] = 'l';
  47. str[4] = 'o';
  48. str[5] = ' ';
  49. str[6] = 'W';
  50. str[7] = 'o';
  51. str[8] = 'r';
  52. str[9] = 'l';
  53. str[10] = 'd';
  54. str[11] = '\n';
  55. str[12] = 0;
  56. int bytes = DkStreamWrite(out, 0, 12, str, NULL);
  57. if (bytes < 0) {
  58. pal_printf("DkStreamWrite failed\n");
  59. return -1;
  60. }
  61. DkVirtualMemoryFree(str, 20);
  62. DkThreadExit();
  63. }
  64. else {
  65. pal_printf("in the parent\n");
  66. DkThreadDelayExecution(3000);
  67. }
  68. DkObjectClose(out);
  69. pal_printf("Leave Main Thread\n");
  70. return 0;
  71. }