Skip to content
Advertisement

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. I can get PID or process handle of the process that my program is to monitor.

Are there any possible approaches that I could take?

Advertisement

Answer

Linux 5.3 introduced pidfd_open, which lets you get a file descriptor from a PID. The FD will become readable when the process dies, which you can detect with select/poll/epoll, like this:

#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;
}
Advertisement