Search code examples
cforkposixwait

What's the difference between while(wait(NULL)){} and while(wait(NULL) > 0){} when using fork


I have the following piece of code:

#include<stdio.h>
#include<stdlib.h> 
#include<sys/wait.h> 
#include<unistd.h> 

int main() {
for(int i = 0; i <3; i++){
    fork();
}
while(wait(NULL)){}
printf("Text\n");
return 0;
}

When I try to execute it, I receive a SIGKILL error, instead of getting 8 Text messages, from the fork call. However, If I change

while(wait(NULL)){}

to

while(wait(NULL) == 0){} 

or

while(wait(NULL) > 0){}

I'm receiving 8 "Text" prints as expected.

Why isn't the program working in the first case? Isn't wait(NULL) loop or wait(0) loop supposed to wait until all child processes are finished executing?

Thanks for the help!


Solution

  • When you do this:

    while(wait(NULL)){} 
    

    It's the same as:

    while(wait(NULL) != 0){} 
    

    The wait function returns the child pid on success or -1 on error. So the return value will never be 0. This results in an infinite loop.

    Doing this:

    while(wait(NULL) > 0){}
    

    Will loop as long as a child returns, and quit when -1 is returned.