我有父进程,必须创建几个子进程.我发现最好的方法是使用fork+ execl.但是父进程需要知道execl具体的孩子是否失败,我不知道如何实现.
int pid = fork();
if (pid < 0) {
std::cout << "ERROR on fork." << std::endl;
} if (pid == 0) {
execl("/my/program/full/path", (char *)NULL);
exit(1);
}
else {
if (/*child's process execl fails*/) {
std::cout << "it failed" << std::endl
} else {
std::cout << "child born" << std::endl
}
}
我认为这个想法并不好:
int status(0);
sleep(100);
int res = waitpid(pid, &status, WNOHANG);
if (res < 0 && errno == 10) {
std::cout << "it failed" << std::endl
} else {
std::cout << "child born" << std::endl
}
因为希望儿童过程在100毫秒后死亡并不好,我想知道,因为只有那样才会发生.
我还认为为这种检查创建shared_memory或特殊管道连接是针对Bees的Cannon.
必须有简单的解决方案,我还没有找到.
实现这一目标的最佳方法是什么?