1
0

hproc.h 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. #ifndef HV_PROC_H_
  2. #define HV_PROC_H_
  3. #include "hplatform.h"
  4. typedef struct proc_ctx_s {
  5. pid_t pid; // tid in win32
  6. procedure_t init;
  7. void* init_userdata;
  8. procedure_t proc;
  9. void* proc_userdata;
  10. procedure_t exit;
  11. void* exit_userdata;
  12. } proc_ctx_t;
  13. #ifdef OS_UNIX
  14. // unix use multi-processes
  15. static inline int hproc_spawn(proc_ctx_t* ctx) {
  16. pid_t pid = fork();
  17. if (pid < 0) {
  18. perror("fork");
  19. return -1;
  20. } else if (pid == 0) {
  21. // child proc
  22. ctx->pid = getpid();
  23. if (ctx->init) {
  24. ctx->init(ctx->init_userdata);
  25. }
  26. if (ctx->proc) {
  27. ctx->proc(ctx->proc_userdata);
  28. }
  29. if (ctx->exit) {
  30. ctx->exit(ctx->exit_userdata);
  31. }
  32. exit(0);
  33. } else if (pid > 0) {
  34. // parent proc
  35. ctx->pid = pid;
  36. }
  37. return pid;
  38. }
  39. #elif defined(OS_WIN)
  40. // win32 use multi-threads
  41. static void win_thread(void* userdata) {
  42. proc_ctx_t* ctx = (proc_ctx_t*)userdata;
  43. if (ctx->init) {
  44. ctx->init(ctx->init_userdata);
  45. }
  46. if (ctx->proc) {
  47. ctx->proc(ctx->proc_userdata);
  48. }
  49. if (ctx->exit) {
  50. ctx->exit(ctx->exit_userdata);
  51. }
  52. }
  53. static inline int hproc_spawn(proc_ctx_t* ctx) {
  54. HANDLE h = (HANDLE)_beginthread(win_thread, 0, ctx);
  55. if (h == NULL) {
  56. return -1;
  57. }
  58. int tid = GetThreadId(h);
  59. ctx->pid = tid;
  60. return tid;
  61. }
  62. #endif
  63. #endif // HV_PROC_H_