hmain.cpp.tmpl 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487
  1. #include <signal.h> // for signal,kill...
  2. #include "h.h"
  3. #include "hsysinfo.h"
  4. #include "hmain.h"
  5. main_ctx_t g_main_ctx;
  6. static int create_pidfile();
  7. static void delete_pidfile();
  8. static pid_t getpid_from_pidfile();
  9. int create_pidfile() {
  10. FILE* fp = fopen(g_main_ctx.pidfile, "w");
  11. if (fp == NULL) {
  12. printf("fopen [%s] error: %d\n", g_main_ctx.pidfile, errno);
  13. return -10;
  14. }
  15. char pid[16] = {0};
  16. snprintf(pid, sizeof(pid), "%d\n", g_main_ctx.pid);
  17. fwrite(pid, 1, strlen(pid), fp);
  18. fclose(fp); atexit(delete_pidfile);
  19. hlogd("create_pidfile [%s] pid=%d", g_main_ctx.pidfile, g_main_ctx.pid);
  20. return 0;
  21. }
  22. void delete_pidfile() {
  23. remove(g_main_ctx.pidfile);
  24. hlogd("delete_pidfile [%s]", g_main_ctx.pidfile);
  25. }
  26. pid_t getpid_from_pidfile() {
  27. FILE* fp = fopen(g_main_ctx.pidfile, "r");
  28. if (fp == NULL) {
  29. //printf("fopen [%s] error: %d\n", g_conf_ctx.pidfile, errno);
  30. return -1;
  31. }
  32. char pid[64];
  33. int readbytes = fread(pid, 1, sizeof(pid), fp);
  34. fclose(fp);
  35. if (readbytes <= 0) {
  36. printf("fread [%s] bytes=%d\n", g_main_ctx.pidfile, readbytes);
  37. return -1;
  38. }
  39. return atoi(pid);
  40. }
  41. int main_ctx_init(int argc, char** argv) {
  42. g_main_ctx.pid = getpid();
  43. char* cwd = getcwd(g_main_ctx.run_path, sizeof(g_main_ctx.run_path));
  44. if (cwd == NULL) {
  45. printf("getcwd error\n");
  46. }
  47. //printf("run_path=%s\n", g_main_ctx.run_path);
  48. const char* b = argv[0];
  49. const char* e = b;
  50. while (*e) ++e;
  51. --e;
  52. while (e >= b) {
  53. if (*e == '/' || *e == '\\') {
  54. break;
  55. }
  56. --e;
  57. }
  58. strncpy(g_main_ctx.program_name, e+1, sizeof(g_main_ctx.program_name));
  59. #ifdef _WIN32
  60. if (strcmp(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4, ".exe") == 0) {
  61. *(g_main_ctx.program_name+strlen(g_main_ctx.program_name)-4) = '\0';
  62. }
  63. #endif
  64. //printf("program_name=%s\n", g_main_ctx.program_name);
  65. // save arg
  66. int i = 0;
  67. g_main_ctx.os_argv = argv;
  68. g_main_ctx.argc = 0;
  69. g_main_ctx.arg_len = 0;
  70. for (i = 0; argv[i]; ++i) {
  71. g_main_ctx.arg_len += strlen(argv[i]) + 1;
  72. }
  73. g_main_ctx.argc = i;
  74. char* argp = (char*)malloc(g_main_ctx.arg_len);
  75. memset(argp, 0, g_main_ctx.arg_len);
  76. g_main_ctx.save_argv = (char**)malloc((g_main_ctx.argc+1) * sizeof(char*));
  77. for (i = 0; argv[i]; ++i) {
  78. g_main_ctx.save_argv[i] = argp;
  79. strcpy(g_main_ctx.save_argv[i], argv[i]);
  80. argp += strlen(argv[i]) + 1;
  81. }
  82. g_main_ctx.save_argv[g_main_ctx.argc] = NULL;
  83. // save env
  84. g_main_ctx.os_envp = environ;
  85. g_main_ctx.envc = 0;
  86. g_main_ctx.env_len = 0;
  87. for (i = 0; environ[i]; ++i) {
  88. g_main_ctx.env_len += strlen(environ[i]) + 1;
  89. }
  90. g_main_ctx.envc = i;
  91. char* envp = (char*)malloc(g_main_ctx.env_len);
  92. memset(envp, 0, g_main_ctx.env_len);
  93. g_main_ctx.save_envp = (char**)malloc((g_main_ctx.envc+1) * sizeof(char*));
  94. for (i = 0; environ[i]; ++i) {
  95. g_main_ctx.save_envp[i] = envp;
  96. strcpy(g_main_ctx.save_envp[i], environ[i]);
  97. envp += strlen(environ[i]) + 1;
  98. }
  99. g_main_ctx.save_envp[g_main_ctx.envc] = NULL;
  100. // parse env
  101. for (i = 0; environ[i]; ++i) {
  102. char* b = environ[i];
  103. char* delim = strchr(b, '=');
  104. if (delim == NULL) {
  105. continue;
  106. }
  107. g_main_ctx.env_kv[std::string(b, delim-b)] = std::string(delim+1);
  108. }
  109. /*
  110. // print argv and envp
  111. printf("---------------arg------------------------------\n");
  112. for (auto& pair : g_main_ctx.arg_kv) {
  113. printf("%s=%s\n", pair.first.c_str(), pair.second.c_str());
  114. }
  115. printf("---------------env------------------------------\n");
  116. for (auto& pair : g_main_ctx.env_kv) {
  117. printf("%s=%s\n", pair.first.c_str(), pair.second.c_str());
  118. }
  119. printf("PWD=%s\n", get_env("PWD"));
  120. printf("USER=%s\n", get_env("USER"));
  121. printf("HOME=%s\n", get_env("HOME"));
  122. printf("LANG=%s\n", get_env("LANG"));
  123. printf("TERM=%s\n", get_env("TERM"));
  124. printf("SHELL=%s\n", get_env("SHELL"));
  125. printf("================================================\n");
  126. */
  127. char logpath[MAX_PATH] = {0};
  128. snprintf(logpath, sizeof(logpath), "%s/logs", g_main_ctx.run_path);
  129. MKDIR(logpath);
  130. snprintf(g_main_ctx.confile, sizeof(g_main_ctx.confile), "%s/etc/%s.conf", g_main_ctx.run_path, g_main_ctx.program_name);
  131. snprintf(g_main_ctx.pidfile, sizeof(g_main_ctx.pidfile), "%s/logs/%s.pid", g_main_ctx.run_path, g_main_ctx.program_name);
  132. snprintf(g_main_ctx.logfile, sizeof(g_main_ctx.confile), "%s/logs/%s.log", g_main_ctx.run_path, g_main_ctx.program_name);
  133. g_main_ctx.confile_parser = NULL;
  134. g_main_ctx.oldpid = getpid_from_pidfile();
  135. #ifdef __unix__
  136. if (kill(g_main_ctx.oldpid, 0) == -1 && errno == ESRCH) {
  137. g_main_ctx.oldpid = -1;
  138. }
  139. #else
  140. #endif
  141. return 0;
  142. }
  143. const char* get_arg(const char* key) {
  144. auto iter = g_main_ctx.arg_kv.find(key);
  145. if (iter == g_main_ctx.arg_kv.end()) {
  146. return NULL;
  147. }
  148. return iter->second.c_str();
  149. }
  150. const char* get_env(const char* key) {
  151. auto iter = g_main_ctx.env_kv.find(key);
  152. if (iter == g_main_ctx.env_kv.end()) {
  153. return NULL;
  154. }
  155. return iter->second.c_str();
  156. }
  157. #ifdef __unix__
  158. /*
  159. * memory layout
  160. * argv[0]\0argv[1]\0argv[n]\0env[0]\0env[1]\0env[n]\0
  161. */
  162. void setproctitle(const char* title) {
  163. //printf("proctitle=%s\n", title);
  164. memset(g_main_ctx.os_argv[0], 0, g_main_ctx.arg_len + g_main_ctx.env_len);
  165. strncpy(g_main_ctx.os_argv[0], title, g_main_ctx.arg_len + g_main_ctx.env_len);
  166. }
  167. #endif
  168. // unix short style
  169. static char options[] = "hvc:ts:d";
  170. static char detail_options[] = "\
  171. -h : print help\n\
  172. -v : print version\n\
  173. -c confile : set configure file, default etc/${program}.conf\n\
  174. -t : test configure file and exit\n\
  175. -s signal : send signal to process\n\
  176. signal=[start, stop, restart, status]\n\
  177. -d : daemon\n\
  178. ";
  179. void print_version() {
  180. printf("%s version %s\n", g_main_ctx.program_name, get_compile_version());
  181. }
  182. void print_help() {
  183. printf("Usage: %s [%s]\n", g_main_ctx.program_name, options);
  184. printf("Options:\n%s\n", detail_options);
  185. }
  186. #define INVALID_OPTION -1
  187. #define FLAG_OPTION 1
  188. #define PARMA_OPTION 2
  189. int get_option(char opt) {
  190. char* p = options;
  191. while (*p && *p != opt) ++p;
  192. if (*p == '\0') return INVALID_OPTION;
  193. if (*(p+1) == ':') return PARMA_OPTION;
  194. return FLAG_OPTION;
  195. }
  196. int parse_cmdline(int argc, char** argv) {
  197. int i = 1;
  198. while (argv[i]) {
  199. char* p = argv[i];
  200. if (*p != '-') {
  201. printf("Invalid argv[%d]: %s\n", i, argv[i]);
  202. exit(-10);
  203. }
  204. while (*++p) {
  205. switch (get_option(*p)) {
  206. case INVALID_OPTION:
  207. printf("Invalid option: '%c'\n", *p);
  208. exit(-20);
  209. case FLAG_OPTION:
  210. g_main_ctx.arg_kv[std::string(p, 1)] = "true";
  211. break;
  212. case PARMA_OPTION:
  213. if (*(p+1) != '\0') {
  214. g_main_ctx.arg_kv[std::string(p, 1)] = p+1;
  215. ++i;
  216. goto next_option;
  217. } else if (argv[i+1] != NULL) {
  218. g_main_ctx.arg_kv[std::string(p, 1)] = argv[i+1];
  219. i += 2;
  220. goto next_option;
  221. } else {
  222. printf("Option '%c' requires param\n", *p);
  223. exit(-30);
  224. }
  225. }
  226. }
  227. ++i;
  228. next_option:
  229. continue;
  230. }
  231. return 0;
  232. }
  233. #ifdef __unix__
  234. // unix use signal
  235. // we use SIGTERM to quit process
  236. #define SIGNAL_TERMINATE SIGTERM
  237. #include <sys/wait.h>
  238. #define MAXNUM_WORKER 1024
  239. static pid_t s_worker_processes[MAXNUM_WORKER];
  240. void worker_process_cycle() {
  241. char proctitle[256] = {0};
  242. snprintf(proctitle, sizeof(proctitle), "%s: worker process", g_main_ctx.program_name);
  243. setproctitle(proctitle);
  244. while(1) {
  245. msleep(1);
  246. }
  247. }
  248. int create_worker_process(int worker_processes) {
  249. for (int i = 0; i < worker_processes; ++i) {
  250. pid_t pid = fork();
  251. if (pid < 0) {
  252. hloge("fork error: %d", errno);
  253. return errno;
  254. }
  255. if (pid == 0) {
  256. hlogi("worker process start/running, pid=%d", getpid());
  257. worker_process_cycle();
  258. exit(0);
  259. }
  260. for (int i = 0; i < MAXNUM_WORKER; ++i) {
  261. if (s_worker_processes[i] <= 0) {
  262. s_worker_processes[i] = pid;
  263. break;
  264. }
  265. }
  266. }
  267. return 0;
  268. }
  269. static int s_signo = 0;
  270. void master_process_signal_handler(int signo) {
  271. hlogd("pid=%d recv signo=%d", getpid(), signo);
  272. s_signo = signo;
  273. }
  274. void master_process_init() {
  275. for (int i = 0; i < MAXNUM_WORKER; ++i) {
  276. s_worker_processes[i] = -1;
  277. }
  278. }
  279. void master_process_cycle() {
  280. char proctitle[256] = {0};
  281. snprintf(proctitle, sizeof(proctitle), "%s: master process", g_main_ctx.program_name);
  282. setproctitle(proctitle);
  283. signal(SIGINT, master_process_signal_handler);
  284. signal(SIGCHLD, master_process_signal_handler);
  285. signal(SIGNAL_TERMINATE, master_process_signal_handler);
  286. sigset_t sigset;
  287. sigemptyset(&sigset);
  288. sigaddset(&sigset, SIGINT);
  289. sigaddset(&sigset, SIGCHLD);
  290. sigaddset(&sigset, SIGNAL_TERMINATE);
  291. sigprocmask(SIG_BLOCK, &sigset, NULL);
  292. create_worker_process(get_ncpu());
  293. sigemptyset(&sigset);
  294. while (1) {
  295. sigsuspend(&sigset);
  296. switch (s_signo) {
  297. case SIGINT:
  298. case SIGNAL_TERMINATE:
  299. hlogi("killall worker processes");
  300. for (int i = 0; i < MAXNUM_WORKER; ++i) {
  301. if (s_worker_processes[i] <= 0) break;
  302. kill(s_worker_processes[i], SIGKILL);
  303. s_worker_processes[i] = -1;
  304. }
  305. msleep(1000);
  306. exit(0);
  307. break;
  308. case SIGCHLD:
  309. {
  310. pid_t pid = 0;
  311. int status = 0;
  312. while ((pid = waitpid(-1, &status, WNOHANG)) > 0) {
  313. hlogw("worker process stop/waiting, pid=%d status=%d", pid, status);
  314. for (int i = 0; i < MAXNUM_WORKER; ++i) {
  315. if (s_worker_processes[i] == pid) {
  316. s_worker_processes[i] = -1;
  317. break;
  318. }
  319. }
  320. create_worker_process(1);
  321. }
  322. }
  323. break;
  324. default:
  325. break;
  326. }
  327. }
  328. }
  329. #else
  330. // win32 use Event
  331. static HANDLE s_hEventTerm = NULL;
  332. void master_process_exit() {
  333. CloseHandle(s_hEventTerm);
  334. s_hEventTerm = NULL;
  335. }
  336. void master_process_init() {
  337. char eventname[MAX_PATH] = {0};
  338. snprintf(eventname, sizeof(eventname), "%s_term_event", g_main_ctx.program_name);
  339. s_hEventTerm = CreateEvent(NULL, FALSE, FALSE, eventname);
  340. //s_hEventTerm = OpenEvent(EVENT_ALL_ACCESS, FALSE, eventname);
  341. atexit(master_process_exit);
  342. }
  343. void master_process_cycle() {
  344. while (1) {
  345. DWORD ret = WaitForSingleObject(s_hEventTerm, INFINITE);
  346. exit(0);
  347. }
  348. }
  349. #endif
  350. int main(int argc, char** argv) {
  351. main_ctx_init(argc, argv);
  352. parse_cmdline(argc, argv);
  353. master_process_init();
  354. if (get_arg("h")) {
  355. print_help();
  356. exit(0);
  357. }
  358. if (get_arg("v")) {
  359. print_version();
  360. exit(0);
  361. }
  362. const char* confile = get_arg("c");
  363. if (confile) {
  364. strncpy(g_main_ctx.confile, confile, sizeof(g_main_ctx.confile));
  365. }
  366. //printf("load confile [%s]\n", g_conf_ctx.confile);
  367. if (get_arg("t")) {
  368. exit(0);
  369. }
  370. const char* signal = get_arg("s");
  371. if (signal) {
  372. if (strcmp(signal, "start") == 0) {
  373. if (g_main_ctx.oldpid > 0) {
  374. printf("%s is already running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  375. exit(0);
  376. }
  377. } else if (strcmp(signal, "stop") == 0) {
  378. if (g_main_ctx.oldpid > 0) {
  379. #ifdef __unix__
  380. kill(g_main_ctx.oldpid, SIGNAL_TERMINATE);
  381. #else
  382. SetEvent(s_hEventTerm);
  383. #endif
  384. printf("%s stop/waiting\n", g_main_ctx.program_name);
  385. } else {
  386. printf("%s is already stopped", g_main_ctx.program_name);
  387. }
  388. exit(0);
  389. } else if (strcmp(signal, "restart") == 0) {
  390. if (g_main_ctx.oldpid > 0) {
  391. #ifdef __unix__
  392. kill(g_main_ctx.oldpid, SIGNAL_TERMINATE);
  393. #else
  394. SetEvent(s_hEventTerm);
  395. #endif
  396. printf("%s stop/waiting\n", g_main_ctx.program_name);
  397. msleep(1000);
  398. }
  399. } else if (strcmp(signal, "status") == 0) {
  400. if (g_main_ctx.oldpid > 0) {
  401. printf("%s start/running, pid=%d\n", g_main_ctx.program_name, g_main_ctx.oldpid);
  402. } else {
  403. printf("%s stop/waiting\n", g_main_ctx.program_name);
  404. }
  405. exit(0);
  406. } else {
  407. printf("Invalid signal: '%s'\n", signal);
  408. exit(0);
  409. }
  410. printf("%s start/running\n", g_main_ctx.program_name);
  411. }
  412. #ifdef __unix__
  413. if (get_arg("d")) {
  414. // nochdir, noclose
  415. int ret = daemon(1, 1);
  416. if (ret != 0) {
  417. printf("daemon error: %d\n", ret);
  418. exit(-10);
  419. }
  420. // parent process exit after daemon, so pid changed.
  421. g_main_ctx.pid = getpid();
  422. }
  423. #endif
  424. hlog_set_file(g_main_ctx.logfile);
  425. hlog_set_level(LOG_LEVEL_DEBUG);
  426. hlogi("%s version: %s", g_main_ctx.program_name, get_compile_version());
  427. hlogi("%s start/running, pid=%d", g_main_ctx.program_name, g_main_ctx.pid);
  428. create_pidfile();
  429. master_process_cycle();
  430. return 0;
  431. }