我通过fork()创建了多个子进程,并让它们通过exec()运行可执行文件。
我想检查是否有任何失败(Exc:):尝试执行不存在的文件。通过,尝试执行所有程序,如果其中一个失败,则在开始与任何程序通信之前返回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;
}
这个程序仍然发送消息到“不存在”(但没有收到任何东西作为预期)。
有什么方法可以达到我的目标吗?谢谢您!
最佳答案
您可以将apipe()
的一端设置为exec时关闭。execl()
失败后(即,如果调用返回),子项将write()
到管道。如果父级在其管道末端接收到任何内容(使用poll()
或类似选项进行检查),则它知道子级已失败。
如果来自子级的消息包含子级的标识符,则可以跨所有子级共享管道。不过,还是要尽量保持write()
小到原子级!
关于c - 如何检查execl()是否成功(多个进程),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39778550/