hproc.h 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  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 Windows
  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. static inline void hproc_run(proc_ctx_t* ctx) {
  14. if (ctx->init) {
  15. ctx->init(ctx->init_userdata);
  16. }
  17. if (ctx->proc) {
  18. ctx->proc(ctx->proc_userdata);
  19. }
  20. if (ctx->exit) {
  21. ctx->exit(ctx->exit_userdata);
  22. }
  23. }
  24. #ifdef OS_UNIX
  25. // unix use multi-processes
  26. static inline int hproc_spawn(proc_ctx_t* ctx) {
  27. pid_t pid = fork();
  28. if (pid < 0) {
  29. perror("fork");
  30. return -1;
  31. } else if (pid == 0) {
  32. // child process
  33. ctx->pid = getpid();
  34. hproc_run(ctx);
  35. exit(0);
  36. } else if (pid > 0) {
  37. // parent process
  38. ctx->pid = pid;
  39. }
  40. return pid;
  41. }
  42. #elif defined(OS_WIN)
  43. // win32 use multi-threads
  44. static void win_thread(void* userdata) {
  45. proc_ctx_t* ctx = (proc_ctx_t*)userdata;
  46. ctx->pid = GetCurrentThreadId(); // tid in Windows
  47. hproc_run(ctx);
  48. }
  49. static inline int hproc_spawn(proc_ctx_t* ctx) {
  50. HANDLE h = (HANDLE)_beginthread(win_thread, 0, ctx);
  51. if (h == NULL) {
  52. return -1;
  53. }
  54. ctx->pid = GetThreadId(h); // tid in Windows
  55. return ctx->pid;
  56. }
  57. #endif
  58. #endif // HV_PROC_H_