hproc.h 1.5 KB

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