想写一个类似 watchdog 的程序,监听一个进程是否存活 (如果进程死亡就重启进程)。因为这个进程没有 health check,也不是 watchdog 的子进程 (因为 watchdog 也会重启),所以没想到什么好的方式判断。我能想到的方式有几种:
想请教下大家最正确的判断方式是什么。
|  |      1opensail      2020-12-26 10:51:17 +08:00 via Android  1 static bool check_pid(char *pid_file) {  struct stat stb; FILE *pidfile; if (stat(pid_file, &stb) == 0) { pidfile = fopen(pid_file, "r"); if (pidfile) { char buf[64]; pid_t pid = 0; memset(buf, 0, sizeof(buf)); if (fread(buf, 1, sizeof(buf), pidfile)) { buf[sizeof(buf) - 1] = '\0'; pid = atoi(buf); } fclose(pidfile); if (pid && kill(pid, 0) == 0) { return 1; } } printf("removing pidfile '%s',process not runing", pid_file); unlink(pid_file); } return 0; } | 
|  |      2opensail      2020-12-26 10:52:40 +08:00 via Android  1 基本是和楼主思路一致,书上也是这样说的,判断 pid | 
|  |      3codehz      2020-12-26 10:57:33 +08:00 via Android  1 用 pidfd,降低出问题的可能性(指竞争条件) | 
|  |      4love      2020-12-26 11:30:36 +08:00 via Android  1 直接在所有进程列表查找对应的进程命令行 pattern 不就行了,pid 都不需要 | 
|  |      5f6x      2020-12-26 11:46:35 +08:00  1 kill(pid, 0)  标准用法 | 
|  |      6ihipop      2020-12-26 11:57:41 +08:00 via Android  2 死亡的标准是什么?进程退出?那 systemd 就可以帮你自动重启,不需要什么 watchdog,至于 kill pid 也是不准,因为 pid 是可以被循环♻使用的,,pid 存在不代表那个 pid 就是你原来的程序 | 
|  |      7lzdhlsc OP @ihipop 嗯,其实 systemd 是最好的。我想做的是一个类似 kubelet 的东西,根据 spec 来管理进程,不知道能不能用 systemd 。 | 
|  |      10ysc3839      2020-12-26 12:37:10 +08:00 via Android  1 @lzdhlsc 保证不了,要通过进程启动时间来判断是否重复使用了。如果确认重复使用了,也能确认原进程退出了。 | 
|  |      11codehz      2020-12-26 12:39:48 +08:00 via Android  1 @ysc3839 pidfd 可以保证的( 就算重用了也能拿到之前死了的通知,然后这个 fd 失效不能再读取 | 
|  |      12mickeyworks      2020-12-26 12:42:55 +08:00  1 找两篇 liunx 挖矿分析文章,看一下里面监控模块怎么写的。。。 | 
|      13julyclyde      2020-12-27 08:41:53 +08:00  1 zombie 也有 status 文件的 kill -0 是正确答案 |