Reputation: 37
I am writing a program where multiple child processes can be created and the parent process continues to execute even while the child processes have not been terminated. However, once they are terminated, I want them to be printed before prompting the user to create more child processes.
From my understanding of(waitpid((pid_t)-1, NULL, WNOHANG), it should wait and check for all terminated child processes
does it return multiple return values for each terminated child process?
pid_t temp;
while(waitpid((pid_t)-1, NULL, WNOHANG)){
temp = (waitpid((pid_t)-1, NULL, WNOHANG)
if(temp == -1)
//error code
else if(temp == 0)
break;
else{
//fprintf pid of terminated child process
//this statement never gets executed when I run the code
}
}
(Not looking for code; just want to know if I am understanding the concept properly :-/ Read through man for waitpid)
Thank you!
Upvotes: 2
Views: 7367
Reputation: 36401
A much better practice is the use of SIGCHLD
signal which is sent to parent process when one of its children dies. Thus, catching it in parent can let you make every decision you need, for example construct a list of currently died children by waiting the way you basically did (looping on waitpid
in non blocking mode). Beware that each call to waitpid
catches a dead process (don't call it exactly the way you did, there is a comment on this subject). Then just before printing the prompt you can print the content of this list and, at the same time cleaning that list. Be careful to temporarily block SIGCHLD
delivery in the meantime to prevent auto-concurrent list management.
Upvotes: 0