假设我有一个父进程,它会派生几个工作进程(子进程)。 我想在其中一个子进程崩溃(被杀死)时得到通知。
最佳方法是什么呢? 我使用 C 或 C++ 进行编程。 我在 UNIX 上。并且使用 fork_and_exec 派生了子进程。
假设我有一个父进程,它会派生几个工作进程(子进程)。 我想在其中一个子进程崩溃(被杀死)时得到通知。
最佳方法是什么呢? 我使用 C 或 C++ 进行编程。 我在 UNIX 上。并且使用 fork_and_exec 派生了子进程。
#include <iostream>
#include <sys/types.h>
#include <unistd.h>
int spawn(char* process_name, char** arguments){
pid_t child_id = fork();
if (child_id != 0)
return child_id;
else{
execvp(process_name, arguments);
fprintf(stderr, "An error occured while executing new process.\n");
abort();
}
}
int main(int argc, const char * argv[])
{
char* arguments[] = {
"/Path_to_Child_Exe/Child_Process",
nullptr
};
int i=0;
while (i++ < 10)
spawn((char*) "/Path_to_Child_Exe/Child_Process", arguments);
while (true){
siginfo_t exit_info;
int retVal = waitid(P_ALL, -1, &exit_info, WEXITED);
if (retVal == -1 && errno == ECHILD){
std::cout << "No more children.\n";
break;
}
std::cout << "Child with PID " << exit_info.si_pid << " terminated.\n";
sleep(1);
}
return 0;
}
同样值得注意的是,在 while 循环的每次迭代结束时,我们需要调用 sleep。在等待子进程的线程中也应该这样做。否则,如果没有子进程时就调用 waitid() 函数而不暂停,则 CPU 使用率会非常高(我猜这是一种忙等待的形式)。因此,我们必须时不时地调用 sleep,给 CPU 一个休息的机会。