hmain.c 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657
  1. #include "hmain.h"
  2. #include "hbase.h"
  3. #include "hlog.h"
  4. #include "herr.h"
  5. #include "htime.h"
  6. #include "hthread.h"
  7. #ifdef OS_DARWIN
  8. #include <crt_externs.h>
  9. #define environ (*_NSGetEnviron())
  10. #endif
  11. main_ctx_t g_main_ctx;
  12. static void init_arg_kv(int maxsize) {
  13. g_main_ctx.arg_kv_size = 0;
  14. SAFE_ALLOC(g_main_ctx.arg_kv, sizeof(char*) * maxsize);
  15. }
  16. static void save_arg_kv(const char* key, int key_len, const char* val, int val_len) {
  17. if (key_len <= 0) key_len = strlen(key);
  18. if (val_len <= 0) val_len = strlen(val);
  19. char* arg = NULL;
  20. SAFE_ALLOC(arg, key_len + val_len + 2);
  21. memcpy(arg, key, key_len);
  22. arg[key_len] = '=';
  23. memcpy(arg + key_len + 1, val, val_len);
  24. // printf("save_arg_kv: %s\n", arg);
  25. g_main_ctx.arg_kv[g_main_ctx.arg_kv_size++] = arg;
  26. }
  27. static void init_arg_list(int maxsize) {
  28. g_main_ctx.arg_list_size = 0;
  29. SAFE_ALLOC(g_main_ctx.arg_list, sizeof(char*) * maxsize);
  30. }
  31. static void save_arg_list(const char* arg) {
  32. // printf("save_arg_list: %s\n", arg);
  33. g_main_ctx.arg_list[g_main_ctx.arg_list_size++] = strdup(arg);
  34. }
  35. static const char* get_val(char** kvs, const char* key) {
  36. if (kvs == NULL) return NULL;
  37. int key_len = strlen(key);
  38. char* kv = NULL;
  39. int kv_len = 0;
  40. for (int i = 0; kvs[i]; ++i) {
  41. kv = kvs[i];
  42. kv_len = strlen(kv);
  43. if (kv_len <= key_len) continue;
  44. // key=val
  45. if (memcmp(kv, key, key_len) == 0 && kv[key_len] == '=') {
  46. return kv + key_len + 1;
  47. }
  48. }
  49. return NULL;
  50. }
  51. const char* get_arg(const char* key) {
  52. return get_val(g_main_ctx.arg_kv, key);
  53. }
  54. const char* get_env(const char* key) {
  55. return get_val(g_main_ctx.save_envp, key);
  56. }
  57. int main_ctx_init(int argc, char** argv) {
  58. if (argc == 0 || argv == NULL) {
  59. argc = 1;
  60. SAFE_ALLOC(argv, 2 * sizeof(char*));
  61. SAFE_ALLOC(argv[0], MAX_PATH);
  62. get_executable_path(argv[0], MAX_PATH);
  63. }
  64. get_run_dir(g_main_ctx.run_dir, sizeof(g_main_ctx.run_dir));
  65. //printf("run_dir=%s\n", g_main_ctx.run_dir);
  66. strncpy(g_main_ctx.program_name, hv_basename(argv[0]), sizeof(g_main_ctx.program_name));
  67. #ifdef OS_WIN
  68. if (strcmp(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4, ".exe") == 0) {
  69. *(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4) = '\0';
  70. }
  71. #endif
  72. //printf("program_name=%s\n", g_main_ctx.program_name);
  73. char logdir[MAX_PATH] = {0};
  74. snprintf(logdir, sizeof(logdir), "%s/logs", g_main_ctx.run_dir);
  75. hv_mkdir(logdir);
  76. snprintf(g_main_ctx.confile, sizeof(g_main_ctx.confile), "%s/etc/%s.conf", g_main_ctx.run_dir, g_main_ctx.program_name);
  77. snprintf(g_main_ctx.pidfile, sizeof(g_main_ctx.pidfile), "%s/logs/%s.pid", g_main_ctx.run_dir, g_main_ctx.program_name);
  78. snprintf(g_main_ctx.logfile, sizeof(g_main_ctx.confile), "%s/logs/%s.log", g_main_ctx.run_dir, g_main_ctx.program_name);
  79. hlog_set_file(g_main_ctx.logfile);
  80. g_main_ctx.pid = getpid();
  81. g_main_ctx.oldpid = getpid_from_pidfile();
  82. #ifdef OS_UNIX
  83. if (kill(g_main_ctx.oldpid, 0) == -1 && errno == ESRCH) {
  84. g_main_ctx.oldpid = -1;
  85. }
  86. #else
  87. HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, g_main_ctx.oldpid);
  88. if (hproc == NULL) {
  89. g_main_ctx.oldpid = -1;
  90. }
  91. else {
  92. CloseHandle(hproc);
  93. }
  94. #endif
  95. // save arg
  96. int i = 0;
  97. g_main_ctx.os_argv = argv;
  98. g_main_ctx.argc = 0;
  99. g_main_ctx.arg_len = 0;
  100. for (i = 0; argv[i]; ++i) {
  101. g_main_ctx.arg_len += strlen(argv[i]) + 1;
  102. }
  103. g_main_ctx.argc = i;
  104. char* argp = NULL;
  105. SAFE_ALLOC(argp, g_main_ctx.arg_len);
  106. SAFE_ALLOC(g_main_ctx.save_argv, (g_main_ctx.argc + 1) * sizeof(char*));
  107. char* cmdline = NULL;
  108. SAFE_ALLOC(cmdline, g_main_ctx.arg_len);
  109. g_main_ctx.cmdline = cmdline;
  110. for (i = 0; argv[i]; ++i) {
  111. strcpy(argp, argv[i]);
  112. g_main_ctx.save_argv[i] = argp;
  113. argp += strlen(argv[i]) + 1;
  114. strcpy(cmdline, argv[i]);
  115. cmdline += strlen(argv[i]);
  116. *cmdline = ' ';
  117. ++cmdline;
  118. }
  119. g_main_ctx.save_argv[g_main_ctx.argc] = NULL;
  120. g_main_ctx.cmdline[g_main_ctx.arg_len-1] = '\0';
  121. #if defined(OS_WIN) || defined(OS_LINUX) || defined(OS_DARWIN)
  122. // save env
  123. g_main_ctx.os_envp = environ;
  124. g_main_ctx.envc = 0;
  125. g_main_ctx.env_len = 0;
  126. for (i = 0; environ[i]; ++i) {
  127. g_main_ctx.env_len += strlen(environ[i]) + 1;
  128. }
  129. g_main_ctx.envc = i;
  130. char* envp = NULL;
  131. SAFE_ALLOC(envp, g_main_ctx.env_len);
  132. SAFE_ALLOC(g_main_ctx.save_envp, (g_main_ctx.envc + 1) * sizeof(char*));
  133. for (i = 0; environ[i]; ++i) {
  134. g_main_ctx.save_envp[i] = envp;
  135. strcpy(g_main_ctx.save_envp[i], environ[i]);
  136. envp += strlen(environ[i]) + 1;
  137. }
  138. g_main_ctx.save_envp[g_main_ctx.envc] = NULL;
  139. #endif
  140. // signals
  141. g_main_ctx.reload_fn = NULL;
  142. g_main_ctx.reload_userdata = NULL;
  143. // master workers
  144. g_main_ctx.worker_processes = 0;
  145. g_main_ctx.worker_threads = 0;
  146. g_main_ctx.worker_fn = 0;
  147. g_main_ctx.worker_userdata = 0;
  148. g_main_ctx.proc_ctxs = NULL;
  149. return 0;
  150. }
  151. void main_ctx_finish() {
  152. SAFE_FREE( g_main_ctx.save_argv[ 0 ] );
  153. SAFE_FREE( g_main_ctx.save_argv );
  154. SAFE_FREE( g_main_ctx.cmdline );
  155. SAFE_FREE( g_main_ctx.save_envp[ 0 ] );
  156. SAFE_FREE( g_main_ctx.save_envp );
  157. }
  158. #define UNDEFINED_OPTION -1
  159. static int get_arg_type(int short_opt, const char* options) {
  160. if (options == NULL) return UNDEFINED_OPTION;
  161. const char* p = options;
  162. while (*p && *p != short_opt) ++p;
  163. if (*p == '\0') return UNDEFINED_OPTION;
  164. if (*(p+1) == ':') return REQUIRED_ARGUMENT;
  165. return NO_ARGUMENT;
  166. }
  167. int parse_opt(int argc, char** argv, const char* options) {
  168. if (argc < 1) return 0;
  169. init_arg_kv(strlen(options) + 1);
  170. init_arg_list(argc);
  171. for (int i = 1; argv[i]; ++i) {
  172. char* p = argv[i];
  173. if (*p != '-') {
  174. save_arg_list(argv[i]);
  175. continue;
  176. }
  177. while (*++p) {
  178. int arg_type = get_arg_type(*p, options);
  179. if (arg_type == UNDEFINED_OPTION) {
  180. printf("Invalid option '%c'\n", *p);
  181. return -20;
  182. } else if (arg_type == NO_ARGUMENT) {
  183. save_arg_kv(p, 1, OPTION_ENABLE, 0);
  184. continue;
  185. } else if (arg_type == REQUIRED_ARGUMENT) {
  186. if (*(p+1) != '\0') {
  187. save_arg_kv(p, 1, p+1, 0);
  188. break;
  189. } else if (argv[i+1] != NULL) {
  190. save_arg_kv(p, 1, argv[++i], 0);
  191. break;
  192. } else {
  193. printf("Option '%c' requires param\n", *p);
  194. return -30;
  195. }
  196. }
  197. }
  198. }
  199. return 0;
  200. }
  201. static const option_t* get_option(const char* opt, const option_t* long_options, int size) {
  202. if (opt == NULL || long_options == NULL) return NULL;
  203. int len = strlen(opt);
  204. if (len == 0) return NULL;
  205. if (len == 1) {
  206. for (int i = 0; i < size; ++i) {
  207. if (long_options[i].short_opt == *opt) {
  208. return &long_options[i];
  209. }
  210. }
  211. } else {
  212. for (int i = 0; i < size; ++i) {
  213. if (strcmp(long_options[i].long_opt, opt) == 0) {
  214. return &long_options[i];
  215. }
  216. }
  217. }
  218. return NULL;
  219. }
  220. #define MAX_OPTION 32
  221. // opt type
  222. #define NOPREFIX_OPTION 0
  223. #define SHORT_OPTION -1
  224. #define LONG_OPTION -2
  225. int parse_opt_long(int argc, char** argv, const option_t* long_options, int size) {
  226. if (argc < 1) return 0;
  227. init_arg_kv(size + 1);
  228. init_arg_list(argc);
  229. char opt[MAX_OPTION+1] = {0};
  230. for (int i = 1; argv[i]; ++i) {
  231. char* arg = argv[i];
  232. int opt_type = NOPREFIX_OPTION;
  233. // prefix
  234. if (*arg == OPTION_PREFIX) {
  235. ++arg;
  236. opt_type = SHORT_OPTION;
  237. if (*arg == OPTION_PREFIX) {
  238. ++arg;
  239. opt_type = LONG_OPTION;
  240. }
  241. }
  242. int arg_len = strlen(arg);
  243. // delim
  244. char* delim = strchr(arg, OPTION_DELIM);
  245. if (delim) {
  246. if (delim == arg || delim == arg+arg_len-1 || delim-arg > MAX_OPTION) {
  247. printf("Invalid option '%s'\n", argv[i]);
  248. return -10;
  249. }
  250. memcpy(opt, arg, delim-arg);
  251. opt[delim-arg] = '\0';
  252. } else {
  253. if (opt_type == SHORT_OPTION) {
  254. *opt = *arg;
  255. opt[1] = '\0';
  256. } else {
  257. strncpy(opt, arg, MAX_OPTION);
  258. }
  259. }
  260. // get_option
  261. const option_t* pOption = get_option(opt, long_options, size);
  262. if (pOption == NULL) {
  263. if (delim == NULL && opt_type == NOPREFIX_OPTION) {
  264. save_arg_list(arg);
  265. continue;
  266. } else {
  267. printf("Invalid option: '%s'\n", argv[i]);
  268. return -10;
  269. }
  270. }
  271. const char* value = NULL;
  272. if (pOption->arg_type == NO_ARGUMENT) {
  273. // -h
  274. value = OPTION_ENABLE;
  275. } else if (pOption->arg_type == REQUIRED_ARGUMENT) {
  276. if (delim) {
  277. // --port=80
  278. value = delim+1;
  279. } else {
  280. if (opt_type == SHORT_OPTION && *(arg+1) != '\0') {
  281. // p80
  282. value = arg+1;
  283. } else if (argv[i+1] != NULL) {
  284. // --port 80
  285. value = argv[++i];
  286. } else {
  287. printf("Option '%s' requires parament\n", opt);
  288. return -20;
  289. }
  290. }
  291. }
  292. // preferred to use short_opt as key
  293. if (pOption->short_opt > 0) {
  294. save_arg_kv(&pOption->short_opt, 1, value, 0);
  295. } else if (pOption->long_opt) {
  296. save_arg_kv(pOption->long_opt, 0, value, 0);
  297. }
  298. }
  299. return 0;
  300. }
  301. #if defined(OS_UNIX) && !HAVE_SETPROCTITLE
  302. /*
  303. * memory layout
  304. * argv[0]\0argv[1]\0argv[n]\0env[0]\0env[1]\0env[n]\0
  305. */
  306. void setproctitle(const char* fmt, ...) {
  307. char buf[256] = {0};
  308. va_list ap;
  309. va_start(ap, fmt);
  310. vsnprintf(buf, sizeof(buf) - 1, fmt, ap);
  311. va_end(ap);
  312. int len = g_main_ctx.arg_len + g_main_ctx.env_len;
  313. if (g_main_ctx.os_argv && len) {
  314. strncpy(g_main_ctx.os_argv[0], buf, len-1);
  315. }
  316. }
  317. #endif
  318. int create_pidfile() {
  319. FILE* fp = fopen(g_main_ctx.pidfile, "w");
  320. if (fp == NULL) {
  321. hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno);
  322. return -1;
  323. }
  324. g_main_ctx.pid = hv_getpid();
  325. fprintf(fp, "%d\n", (int)g_main_ctx.pid);
  326. fclose(fp);
  327. hlogi("create_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  328. atexit(delete_pidfile);
  329. return 0;
  330. }
  331. void delete_pidfile() {
  332. hlogi("delete_pidfile('%s') pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  333. remove(g_main_ctx.pidfile);
  334. }
  335. pid_t getpid_from_pidfile() {
  336. FILE* fp = fopen(g_main_ctx.pidfile, "r");
  337. if (fp == NULL) {
  338. // hloge("fopen('%s') error: %d", g_main_ctx.pidfile, errno);
  339. return -1;
  340. }
  341. int pid = -1;
  342. fscanf(fp, "%d", &pid);
  343. fclose(fp);
  344. return pid;
  345. }
  346. #ifdef OS_UNIX
  347. // unix use signal
  348. #include <sys/wait.h>
  349. void signal_handler(int signo) {
  350. hlogi("pid=%d recv signo=%d", getpid(), signo);
  351. switch (signo) {
  352. case SIGINT:
  353. case SIGNAL_TERMINATE:
  354. hlogi("killall processes");
  355. signal(SIGCHLD, SIG_IGN);
  356. // master send SIGKILL => workers
  357. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  358. if (g_main_ctx.proc_ctxs[i].pid <= 0) break;
  359. kill(g_main_ctx.proc_ctxs[i].pid, SIGKILL);
  360. g_main_ctx.proc_ctxs[i].pid = -1;
  361. }
  362. exit(0);
  363. break;
  364. case SIGCHLD:
  365. {
  366. pid_t pid = 0;
  367. int status = 0;
  368. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  369. hlogw("proc stop/waiting, pid=%d status=%d", pid, status);
  370. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  371. proc_ctx_t* ctx = g_main_ctx.proc_ctxs + i;
  372. if (ctx->pid == pid) {
  373. ctx->pid = -1;
  374. // NOTE: avoid frequent crash and restart
  375. time_t run_time = time(NULL) - ctx->start_time;
  376. if (ctx->spawn_cnt < 3 || run_time > 3600) {
  377. hproc_spawn(ctx);
  378. }
  379. else {
  380. hloge("proc crash, pid=%d spawn_cnt=%d run_time=%us",
  381. pid, ctx->spawn_cnt, (unsigned int)run_time);
  382. bool have_worker = false;
  383. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  384. if (g_main_ctx.proc_ctxs[i].pid > 0) {
  385. have_worker = true;
  386. break;
  387. }
  388. }
  389. if (!have_worker) {
  390. hlogw("No alive worker process, exit master process!");
  391. exit(0);
  392. }
  393. }
  394. break;
  395. }
  396. }
  397. }
  398. }
  399. break;
  400. case SIGNAL_RELOAD:
  401. if (g_main_ctx.reload_fn) {
  402. g_main_ctx.reload_fn(g_main_ctx.reload_userdata);
  403. if (getpid_from_pidfile() == getpid()) {
  404. // master send SIGNAL_RELOAD => workers
  405. for (int i = 0; i < g_main_ctx.worker_processes; ++i) {
  406. if (g_main_ctx.proc_ctxs[i].pid <= 0) break;
  407. kill(g_main_ctx.proc_ctxs[i].pid, SIGNAL_RELOAD);
  408. }
  409. }
  410. }
  411. break;
  412. default:
  413. break;
  414. }
  415. }
  416. int signal_init(procedure_t reload_fn, void* reload_userdata) {
  417. g_main_ctx.reload_fn = reload_fn;
  418. g_main_ctx.reload_userdata = reload_userdata;
  419. signal(SIGINT, signal_handler);
  420. signal(SIGCHLD, signal_handler);
  421. signal(SIGNAL_TERMINATE, signal_handler);
  422. signal(SIGNAL_RELOAD, signal_handler);
  423. return 0;
  424. }
  425. #elif defined(OS_WIN)
  426. #include <mmsystem.h> // for timeSetEvent
  427. // win32 use Event
  428. //static HANDLE s_hEventTerm = NULL;
  429. static HANDLE s_hEventReload = NULL;
  430. static void WINAPI on_timer(UINT uTimerID, UINT uMsg, DWORD_PTR dwUser, DWORD_PTR dw1, DWORD_PTR dw2) {
  431. DWORD ret;
  432. /*
  433. ret = WaitForSingleObject(s_hEventTerm, 0);
  434. if (ret == WAIT_OBJECT_0) {
  435. hlogi("pid=%d recv event [TERM]", getpid());
  436. if (getpid_from_pidfile() == getpid()) {
  437. timeKillEvent(uTimerID);
  438. exit(0);
  439. }
  440. }
  441. */
  442. ret = WaitForSingleObject(s_hEventReload, 0);
  443. if (ret == WAIT_OBJECT_0) {
  444. hlogi("pid=%d recv event [RELOAD]", getpid());
  445. if (g_main_ctx.reload_fn) {
  446. g_main_ctx.reload_fn(g_main_ctx.reload_userdata);
  447. }
  448. }
  449. }
  450. static void signal_cleanup() {
  451. //CloseHandle(s_hEventTerm);
  452. //s_hEventTerm = NULL;
  453. CloseHandle(s_hEventReload);
  454. s_hEventReload = NULL;
  455. }
  456. int signal_init(procedure_t reload_fn, void* reload_userdata) {
  457. g_main_ctx.reload_fn = reload_fn;
  458. g_main_ctx.reload_userdata = reload_userdata;
  459. char eventname[MAX_PATH] = {0};
  460. //snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name);
  461. //s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname);
  462. //s_hEventTerm = OpenEvent(EVENT_ALL_ACCESS, FALSE, eventname);
  463. snprintf(eventname, sizeof(eventname), "%s_reload_event", g_main_ctx.program_name);
  464. s_hEventReload = CreateEvent(NULL, FALSE, FALSE, eventname);
  465. timeSetEvent(1000, 1000, on_timer, 0, TIME_PERIODIC);
  466. atexit(signal_cleanup);
  467. return 0;
  468. }
  469. #endif
  470. static void kill_proc(int pid) {
  471. #ifdef OS_UNIX
  472. kill(pid, SIGNAL_TERMINATE);
  473. #else
  474. //SetEvent(s_hEventTerm);
  475. //hv_sleep(1);
  476. HANDLE hproc = OpenProcess(PROCESS_TERMINATE, FALSE, pid);
  477. if (hproc) {
  478. TerminateProcess(hproc, 0);
  479. CloseHandle(hproc);
  480. }
  481. #endif
  482. }
  483. void signal_handle(const char* signal) {
  484. if (strcmp(signal, "start") == 0) {
  485. if (g_main_ctx.oldpid > 0) {
  486. printf("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  487. exit(0);
  488. }
  489. } else if (strcmp(signal, "stop") == 0) {
  490. if (g_main_ctx.oldpid > 0) {
  491. kill_proc(g_main_ctx.oldpid);
  492. printf("%s stop/waiting\n", g_main_ctx.program_name);
  493. } else {
  494. printf("%s is already stopped\n", g_main_ctx.program_name);
  495. }
  496. exit(0);
  497. } else if (strcmp(signal, "restart") == 0) {
  498. if (g_main_ctx.oldpid > 0) {
  499. kill_proc(g_main_ctx.oldpid);
  500. printf("%s stop/waiting\n", g_main_ctx.program_name);
  501. hv_sleep(1);
  502. }
  503. } else if (strcmp(signal, "status") == 0) {
  504. if (g_main_ctx.oldpid > 0) {
  505. printf("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  506. } else {
  507. printf("%s stop/waiting\n", g_main_ctx.program_name);
  508. }
  509. exit(0);
  510. } else if (strcmp(signal, "reload") == 0) {
  511. if (g_main_ctx.oldpid > 0) {
  512. printf("reload confile [%s]\n", g_main_ctx.confile);
  513. #ifdef OS_UNIX
  514. kill(g_main_ctx.oldpid, SIGNAL_RELOAD);
  515. #else
  516. SetEvent(s_hEventReload);
  517. #endif
  518. }
  519. hv_sleep(1);
  520. exit(0);
  521. } else {
  522. printf("Invalid signal: '%s'\n", signal);
  523. exit(0);
  524. }
  525. printf("%s start/running\n", g_main_ctx.program_name);
  526. }
  527. // master-workers processes
  528. static HTHREAD_ROUTINE(worker_thread) {
  529. hlogi("worker_thread pid=%ld tid=%ld", hv_getpid(), hv_gettid());
  530. if (g_main_ctx.worker_fn) {
  531. g_main_ctx.worker_fn(g_main_ctx.worker_userdata);
  532. }
  533. return 0;
  534. }
  535. static void worker_init(void* userdata) {
  536. #ifdef OS_UNIX
  537. setproctitle("%s: worker process", g_main_ctx.program_name);
  538. signal(SIGNAL_RELOAD, signal_handler);
  539. #endif
  540. }
  541. static void worker_proc(void* userdata) {
  542. for (int i = 1; i < g_main_ctx.worker_threads; ++i) {
  543. hthread_create(worker_thread, NULL);
  544. }
  545. worker_thread(NULL);
  546. }
  547. int master_workers_run(procedure_t worker_fn, void* worker_userdata,
  548. int worker_processes, int worker_threads, bool wait) {
  549. #ifdef OS_WIN
  550. // NOTE: Windows not provide MultiProcesses
  551. if (worker_threads == 0) {
  552. // MultiProcesses => MultiThreads
  553. worker_threads = worker_processes;
  554. }
  555. worker_processes = 0;
  556. #endif
  557. if (worker_threads == 0) worker_threads = 1;
  558. g_main_ctx.worker_threads = worker_threads;
  559. g_main_ctx.worker_fn = worker_fn;
  560. g_main_ctx.worker_userdata = worker_userdata;
  561. if (worker_processes == 0) {
  562. // single process
  563. if (wait) {
  564. for (int i = 1; i < worker_threads; ++i) {
  565. hthread_create(worker_thread, NULL);
  566. }
  567. worker_thread(NULL);
  568. }
  569. else {
  570. for (int i = 0; i < worker_threads; ++i) {
  571. hthread_create(worker_thread, NULL);
  572. }
  573. }
  574. }
  575. else {
  576. if (g_main_ctx.worker_processes != 0) {
  577. return ERR_OVER_LIMIT;
  578. }
  579. // master-workers processes
  580. #ifdef OS_UNIX
  581. setproctitle("%s: master process", g_main_ctx.program_name);
  582. signal(SIGNAL_RELOAD, signal_handler);
  583. #endif
  584. g_main_ctx.worker_processes = worker_processes;
  585. int bytes = g_main_ctx.worker_processes * sizeof(proc_ctx_t);
  586. SAFE_ALLOC(g_main_ctx.proc_ctxs, bytes);
  587. proc_ctx_t* ctx = g_main_ctx.proc_ctxs;
  588. for (int i = 0; i < g_main_ctx.worker_processes; ++i, ++ctx) {
  589. ctx->init = worker_init;
  590. ctx->proc = worker_proc;
  591. hproc_spawn(ctx);
  592. hlogi("workers[%d] start/running, pid=%d", i, ctx->pid);
  593. }
  594. g_main_ctx.pid = getpid();
  595. hlogi("master start/running, pid=%d", g_main_ctx.pid);
  596. if (wait) {
  597. while (1) hv_sleep (1);
  598. }
  599. }
  600. return 0;
  601. }