hproc.h 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. #ifndef H_PROC_H_
  2. #define H_PROC_H_
  3. #include "hdef.h"
  4. #include "hplatform.h"
  5. #include "hlog.h"
  6. #include "hmain.h"
  7. typedef struct proc_ctx_s {
  8. pid_t pid; // tid in win32
  9. char proctitle[256];
  10. procedure_t proc;
  11. void* userdata;
  12. } proc_ctx_t;
  13. #ifdef __unix__
  14. // unix use multi-processes
  15. inline int create_proc(proc_ctx_t* ctx) {
  16. pid_t pid = fork();
  17. if (pid < 0) {
  18. hloge("fork error: %d", errno);
  19. return -1;
  20. } else if (pid == 0) {
  21. // child proc
  22. hlogi("proc start/running, pid=%d", getpid());
  23. if (strlen(ctx->proctitle) != 0) {
  24. setproctitle(ctx->proctitle);
  25. }
  26. if (ctx->proc) {
  27. ctx->proc(ctx->userdata);
  28. }
  29. exit(0);
  30. } else if (pid > 0) {
  31. // parent proc
  32. }
  33. ctx->pid = pid;
  34. return pid;
  35. }
  36. #elif defined(_WIN32)
  37. // win32 use multi-threads
  38. inline int create_proc(proc_ctx_t* ctx) {
  39. HANDLE h = (HANDLE)_beginthread(ctx->proc, 0, ctx->userdata);
  40. if (h == NULL) {
  41. hloge("_beginthread error: %d", errno);
  42. return -1;
  43. }
  44. int tid = GetThreadId(h);
  45. ctx->pid = tid;
  46. hlogi("proc start/running, tid=%d", tid);
  47. return tid;
  48. }
  49. #endif
  50. #endif // H_PROC_H_