Linux
在 Linux(可能还有许多 Unix 系统)下,您可以通过使用 ptrace 调用来实现此目的,然后使用 waitpid 等待状态:
手册页:
来自手册页:
ptrace 下的死亡
当一个(可能是多线程的)进程收到终止信号时
(其处置设置为 SIG_DFL 并且其默认操作为
杀死进程),所有线程退出。痕迹报告他们的死亡
到他们的示踪剂。此事件的通知通过
waitpid(2)。
请注意,在某些情况下您需要获得特殊授权。看看/proc/sys/kernel/yama/ptrace_scope。 (如果可以修改目标程序,也可以通过调用ptrace(PTRACE_TRACEME, 0, nullptr, nullptr);改变ptrace的行为
要使用ptrace,首先你必须得到你的进程PID,然后调用PTRACE_ATTACH:
// error checking removed for the sake of clarity
#include <sys/ptrace.h>
pid_t child_pid;
// ... Get your child_pid somehow ...
// 1. attach to your process:
long err;
err = ptrace(PTRACE_ATTACH, child_pid, nullptr, nullptr);
// 2. wait for your process to stop:
int process_status;
err = waitpid(child_pid, &process_status, 0);
// 3. restart the process (continue)
ptrace(PTRACE_CONT, child_pid, nullptr, nullptr);
// 4. wait for any change in status:
err = waitpid(child_pid, &process_status, 0);
// while waiting, the process is running...
// by default waitpid will wait for process to terminate, but you can
// change this with WNOHANG in the options.
if (WIFEXITED(status)) {
// exitted
}
if (WIFSIGNALED(status)) {
// process got a signal
// WTERMSIG(status) will get you the signal that was sent.
}
AIX:
该解决方案需要进行一些调整才能与 AIX 一起使用,请查看那里的文档:
Solaris
正如提到的here ptrace 可能在您的 Solaris 版本上不可用,您可能不得不求助于那里的 procfs。