hproc.h 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  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. #include <process.h>
  39. inline int create_proc(proc_ctx_t* ctx) {
  40. HANDLE h = (HANDLE)_beginthread(ctx->proc, 0, ctx->userdata);
  41. if (h == NULL) {
  42. hloge("_beginthread error: %d", errno);
  43. return -1;
  44. }
  45. int tid = GetThreadId(h);
  46. ctx->pid = tid;
  47. hlogi("proc start/running, tid=%d", tid);
  48. return tid;
  49. }
  50. #endif
  51. #endif // H_PROC_H_