I'm attempting to simulate a shell processing foreground commands but I'm running into trouble when it comes to reaping child processes. I spawn multiple processes using fork in the following code.
while (currCmdListNode != list_end(¤tPipeline->commands)) {
if (fork() == 0)
{
printf("Child created with pid %d \n", getpid());
currentCmd = list_entry(currCmdListNode, struct esh_command, elem);
execvp(currentCmd->argv[0], currentCmd->argv);
}
currCmdListNode = list_next(currCmdListNode);
}
Then, I try to reap all these processes from the parent process using the following code.
while((pid = waitpid(-1, &status, WUNTRACED)) > 0)
{
if (WIFEXITED(status))
{
printf("child %d terminated normally with exit status=%d\n", pid, WEXITSTATUS(status));
}
else
{
printf("child %d terminated abnormally\n", pid);
}
}
Let's say I run this code so that two child processes spawn from my initial fork. My reap functionality will return saying it reaped the first child. However, it will hang once it hits waitpid the second time, and I will never get a message saying it reaped the second child. If I spawn four child processes, then maybe two will get reaped, then it will hang. What is going on here? Do I have to do some sort of blocking of the SIGCHLD signal? If so, where should I be blocking it?