在 Linux 中如何判断一个进程是否存活?

2020-12-26 10:38:54 +08:00
 lzdhlsc

想写一个类似 watchdog 的程序,监听一个进程是否存活 (如果进程死亡就重启进程)。因为这个进程没有 health check,也不是 watchdog 的子进程 (因为 watchdog 也会重启),所以没想到什么好的方式判断。我能想到的方式有几种:

  1. 看 /proc/pid 是否存在 + /proc/pid/stat 里面的 status
  2. 调用 kill(pid, 0)

想请教下大家最正确的判断方式是什么。

2277 次点击
所在节点    问与答
14 条回复
opensail
2020-12-26 10:51:17 +08:00
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;
}
opensail
2020-12-26 10:52:40 +08:00
基本是和楼主思路一致,书上也是这样说的,判断 pid
codehz
2020-12-26 10:57:33 +08:00
用 pidfd,降低出问题的可能性(指竞争条件)
love
2020-12-26 11:30:36 +08:00
直接在所有进程列表查找对应的进程命令行 pattern 不就行了,pid 都不需要
f6x
2020-12-26 11:46:35 +08:00
kill(pid, 0) 标准用法
ihipop
2020-12-26 11:57:41 +08:00
死亡的标准是什么?进程退出?那 systemd 就可以帮你自动重启,不需要什么 watchdog,至于 kill pid 也是不准,因为 pid 是可以被循环♻使用的,,pid 存在不代表那个 pid 就是你原来的程序
lzdhlsc
2020-12-26 12:10:07 +08:00
@ihipop 嗯,其实 systemd 是最好的。我想做的是一个类似 kubelet 的东西,根据 spec 来管理进程,不知道能不能用 systemd 。
ysc3839
2020-12-26 12:16:32 +08:00
@ihipop 担心 PID 重复使用,保险的做法还是使用 /proc,顺便读一下进程启动时间。
lzdhlsc
2020-12-26 12:29:35 +08:00
@ysc3839 请问为什么 使用 /proc 可以保证不会重复使用?
ysc3839
2020-12-26 12:37:10 +08:00
@lzdhlsc 保证不了,要通过进程启动时间来判断是否重复使用了。如果确认重复使用了,也能确认原进程退出了。
codehz
2020-12-26 12:39:48 +08:00
@ysc3839 pidfd 可以保证的(
就算重用了也能拿到之前死了的通知,然后这个 fd 失效不能再读取
mickeyworks
2020-12-26 12:42:55 +08:00
找两篇 liunx 挖矿分析文章,看一下里面监控模块怎么写的。。。
julyclyde
2020-12-27 08:41:53 +08:00
zombie 也有 status 文件的
kill -0 是正确答案
julyclyde
2020-12-27 08:43:06 +08:00
@lzdhlsc 正确解法是 systemd 等 SIGCHLD 的方式
从外部而不是上级检查进程是否存活,都是旁门左道。你还得考虑检查频度的问题呢!!

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/739119

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX