hproc.h 1.6 KB

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