我通过 fork() 创建了多个子进程,并让它们通过 execl() 运行可执行文件。
我想检查是否有任何 execl() 失败(例如:尝试执行不存在的文件)。通过,尝试 execl() 所有程序,如果其中一个程序失败,则在 start 与任何程序通信之前返回 1。
这是参考代码,(假设所有设置都正确)
#DEFINE NUMBEROFCHILD 4
char** exeFile = {"./p1", "./p2", "./p3", "nonexist"); //"nonexist" is a non-exist program
int main(int argc, char** argv){
pid_t childPID [numberOfChild];
for (int i = 0; i<numberOfChild; i++) {
//setting up pipes
pid_t childPID[i] = fork();
if(childPID[i] < 0) {
//close all pipes and quit
}else if (childPID[i] == 0) {
//redirect pipe
execl(exeFile[i],"args",(char*)0;
return 1;
//I'm expecting this to return when it try to execute "nonexist"
//but it didn't and keep running successed execl()
}else {
//close un-use pipes
}
}
while(true) {
for (int i = 0; i<numberOfChild; i++) {
//communicate with childs through pipe
}
}
for (int i = 0; i<numberOfChild; i++) {
//close reminded pipes
if (waitpid(childPID[i], NULL, 0) == -1){
return 1;
}
}
return 0;
}
该程序仍然向“不存在”发送消息(但没有按预期收到任何回复)。
有没有办法实现我的目标?谢谢!