简体   繁体   English

如何使用 C++ 在 Linux 中检测进程何时终止?

[英]How to detect when a process is terminated in Linux using C++?

The purpose is I want my program running on Linux to be terminated when some random process is terminated.目的是我希望在某些随机进程终止时终止在 Linux 上运行的程序。 I can get PID or process handle of the process that my program is to monitor.我可以获得程序要监视的进程的 PID 或进程句柄。

Are there any possible approaches that I could take?我可以采取任何可能的方法吗?

Linux 5.3 introduced pidfd_open , which lets you get a file descriptor from a PID. Linux 5.3 引入了pidfd_open ,它允许您从 PID 获取文件描述符。 The FD will become readable when the process dies, which you can detect with select / poll / epoll , like this:当进程终止时,FD 将变得可读,您可以使用select / poll / epoll来检测,如下所示:

#include <iostream>
#include <sys/types.h>
#include <sys/select.h>
#include <sys/syscall.h>
#include <unistd.h>

int main(void) {
    pid_t pid;
    std::cin >> pid;
    int pidfd = syscall(SYS_pidfd_open, pid, 0);
    if(pidfd < 0) {
        perror("pidfd_open");
        return 1;
    }
    fd_set readfds;
    FD_ZERO(&readfds);
    FD_SET(pidfd, &readfds);
    if(select(pidfd + 1, &readfds, nullptr, nullptr, nullptr) != 1) {
        perror("select");
        return 1;
    }
    return 0;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM