hproc.h 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. #ifndef HV_PROC_H_
  2. #define HV_PROC_H_
  3. /*
  4. * @功能:衍生进程
  5. * @备注:unix使用的多进程、windows下使用的多线程
  6. *
  7. */
  8. #include "hplatform.h"
  9. typedef struct proc_ctx_s {
  10. pid_t pid; // tid in Windows
  11. time_t start_time;
  12. int spawn_cnt;
  13. procedure_t init;
  14. void* init_userdata;
  15. procedure_t proc;
  16. void* proc_userdata;
  17. procedure_t exit;
  18. void* exit_userdata;
  19. } proc_ctx_t;
  20. static inline void hproc_run(proc_ctx_t* ctx) {
  21. if (ctx->init) {
  22. ctx->init(ctx->init_userdata);
  23. }
  24. if (ctx->proc) {
  25. ctx->proc(ctx->proc_userdata);
  26. }
  27. if (ctx->exit) {
  28. ctx->exit(ctx->exit_userdata);
  29. }
  30. }
  31. #ifdef OS_UNIX
  32. // unix use multi-processes
  33. static inline int hproc_spawn(proc_ctx_t* ctx) {
  34. ++ctx->spawn_cnt;
  35. ctx->start_time = time(NULL);
  36. pid_t pid = fork();
  37. if (pid < 0) {
  38. perror("fork");
  39. return -1;
  40. } else if (pid == 0) {
  41. // child process
  42. ctx->pid = getpid();
  43. hproc_run(ctx);
  44. exit(0);
  45. } else if (pid > 0) {
  46. // parent process
  47. ctx->pid = pid;
  48. }
  49. return pid;
  50. }
  51. #elif defined(OS_WIN)
  52. // win32 use multi-threads
  53. static void win_thread(void* userdata) {
  54. proc_ctx_t* ctx = (proc_ctx_t*)userdata;
  55. ctx->pid = GetCurrentThreadId(); // tid in Windows
  56. hproc_run(ctx);
  57. }
  58. static inline int hproc_spawn(proc_ctx_t* ctx) {
  59. ++ctx->spawn_cnt;
  60. ctx->start_time = time(NULL);
  61. HANDLE h = (HANDLE)_beginthread(win_thread, 0, ctx);
  62. if (h == NULL) {
  63. return -1;
  64. }
  65. ctx->pid = GetThreadId(h); // tid in Windows
  66. return ctx->pid;
  67. }
  68. #endif
  69. #endif // HV_PROC_H_