开发者

Why could the behavior of a program depend on the order its children finish in?

开发者 https://www.devze.com 2023-03-14 06:13 出处:网络
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开发者_JAVA技巧 third program doesn\'t return... i.e t

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开发者_JAVA技巧 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.


while(wait(&status) != child1);
while(wait(&status) != child2);

In this code - you'll wait until child1 finishes, but if child2 finishes first - you'll get the status and discard it. Then, when child1 finishes - you'll go to the next loop, but then you'll never get the status for child2 because you already discarded it.

Instead, keep an array of children, and loop on wait until you got status for each of the members of the array in a single while loop, then you won't be deadlocked.


That's sounds like the correct behavior for what you describe doing. wait() blocks until the thing it's waiting for happens. If the program waits for several things in a row, it'll have to wait for several things in a row. It sounds like you're using waitpid() instead of wait(). If you use the real wait(), you should just have to call it the same number of times as there are children to wait for.

If you don't care what the order is, make the program not depend on any particular order.

0

精彩评论

暂无评论...
验证码 换一张
取 消