lzdhlsc
V2EX  ›  问与答

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

  •  
  •   lzdhlsc · Dec 26, 2020 · 3683 views
    This topic created in 2150 days ago, the information mentioned may be changed or developed.

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

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

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

    14 replies  •  2020-12-27 08:43:06 +08:00
    opensail
    opensail
    Dec 26, 2020 via Android❤️1
    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;
    }
    opensail
    opensail
    Dec 26, 2020 via Android❤️1
    2
    基本是和楼主思路一致,书上也是这样说的,判断 pid
    codehz
    codehz
    Dec 26, 2020 via Android❤️1
    3
    用 pidfd,降低出问题的可能性(指竞争条件)
    love
    love
    Dec 26, 2020 via Android❤️1
    4
    直接在所有进程列表查找对应的进程命令行 pattern 不就行了,pid 都不需要
    f6x
    f6x
    Dec 26, 2020❤️1
    5
    kill(pid, 0) 标准用法
    ihipop
    ihipop
    Dec 26, 2020 via Android❤️2
    6
    死亡的标准是什么?进程退出?那 systemd 就可以帮你自动重启,不需要什么 watchdog,至于 kill pid 也是不准,因为 pid 是可以被循环♻使用的,,pid 存在不代表那个 pid 就是你原来的程序
    lzdhlsc
    lzdhlsc
    OP
    Dec 26, 2020
    7
    @ihipop 嗯,其实 systemd 是最好的。我想做的是一个类似 kubelet 的东西,根据 spec 来管理进程,不知道能不能用 systemd 。
    ysc3839
    ysc3839
    Dec 26, 2020 via Android❤️1
    8
    @ihipop 担心 PID 重复使用,保险的做法还是使用 /proc,顺便读一下进程启动时间。
    lzdhlsc
    lzdhlsc
    OP
    Dec 26, 2020
    9
    @ysc3839 请问为什么 使用 /proc 可以保证不会重复使用?
    ysc3839
    ysc3839
    Dec 26, 2020 via Android❤️1
    10
    @lzdhlsc 保证不了,要通过进程启动时间来判断是否重复使用了。如果确认重复使用了,也能确认原进程退出了。
    codehz
    codehz
    Dec 26, 2020 via Android❤️1
    11
    @ysc3839 pidfd 可以保证的(
    就算重用了也能拿到之前死了的通知,然后这个 fd 失效不能再读取
    mickeyworks
    mickeyworks
    Dec 26, 2020❤️1
    12
    找两篇 liunx 挖矿分析文章,看一下里面监控模块怎么写的。。。
    julyclyde
    julyclyde
    Dec 27, 2020❤️1
    13
    zombie 也有 status 文件的
    kill -0 是正确答案
    julyclyde
    julyclyde
    Dec 27, 2020❤️1
    14
    @lzdhlsc 正确解法是 systemd 等 SIGCHLD 的方式
    从外部而不是上级检查进程是否存活,都是旁门左道。你还得考虑检查频度的问题呢!!
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   1087 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 38ms · UTC 23:28 · PVG 07:28 · LAX 15:28 · JFK 18:28
    ♥ Do have faith in what you're doing.