我有父进程,必须创建少量子进程。我发现最好的方法是使用fork + execl。但是,然后父进程需要知道具体孩子的execl是否失败,我不知道如何实现。在linux中创建子进程并处理可能的失败的最佳方法
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或特殊管道连接是一个对蜜蜂的加农炮。
必须有简单的解决方案,我只是没有找到。
实现该目标的最佳方法是什么?
2016-05-23
Arkady
+0
只需使用'popen'并检查返回值。 –
+0
假设它还活着,我如何确定execl没有失败?也许它失败了,流程还活着,因为它还没有完成'exit(1)'指令。 –
+0
你想检查你的进程是成功*启动*,还是*完成*和*返回状态为零*?这两者完全不同。 –