2

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?

tunamayo
  • 35
  • 1
  • 4
  • 1
    Does this answer your question? [Check if process exists given its pid](https://stackoverflow.com/questions/9152979/check-if-process-exists-given-its-pid) – kaylum Jun 13 '20 at 05:39
  • It's easy in BSD land, but I've never found a good way for an unrelated process in Linux. – Shawn Jun 13 '20 at 05:55
  • @kaylum No it doesn't, because that's about a one-off check if a process is dead, but this is about getting notified when a process dies. – Joseph Sible-Reinstate Monica Jun 13 '20 at 06:21

1 Answers1

2

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