I run several programs using fork() followed by execve() from a third program. Everything these programs were meant to is done, but at the end the third program doesn’t return… i.e the command prompt does not appear.
If I use a wait() command in the calling program then the execve‘s programs return only if the order of wait statements match the order of the end of the execve programs. Why could it be?
Here’s the simplified code:
int main()
{
int child1,child2,status;
char*newargv1[] = {./xyz",NULL};
char *newargv2[] = {./abc",NULL};
if((child1 = fork())==0)
execve(newargv1[0],newargv1,NULL);
if((child2 = fork())==0)
execve(newargv2[0],newargv2,NULL);
while(wait(&status) != child1);
while(wait(&status) != child2);
}
It works fine if the child1 finishes first. ./xyz and ./abc has some simple processing and control reaches the end.
In this code – you’ll wait until
child1finishes, but ifchild2finishes first – you’ll get the status and discard it. Then, whenchild1finishes – you’ll go to the next loop, but then you’ll never get the status forchild2because you already discarded it.Instead, keep an array of children, and loop on
waituntil you got status for each of the members of the array in a singlewhileloop, then you won’t be deadlocked.