Fork.c 1.9 KB

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