Run the following version of your code (line 58 is added)
Code:
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <time.h>
int randomSleep()
{
srand(time(NULL));
return (rand() % 100);
}
/*
* Main method
* creates children and prints their info
*/
int main(void)
{
int pid, i, x, maxChildren = 5, status, childPid[5];
for(i = 0 ; i < maxChildren ; i++)
{
pid = fork();
if(pid == -1)
{
printf("fork() failed! Child number %d was not created. Retrying...\n", i);
i -= 1;
sleep(1);
exit(0); //child creation failed, exit
}
else if(pid == 0)
{
int currentPid = getpid();
printf("\nParent PID %d, child %d PID %d, group PID %d\n", getppid(), i, currentPid, getpgrp());
childPid[i] = currentPid;
exit(0);
}
else
{
//create a random number from 1-10
srand(time(NULL));
int sleepSecond = (rand() % 10) + 1;
//sleep after each child did some work
printf("sleep for %d sec\n", sleepSecond);
sleep(sleepSecond);
if(i >= (maxChildren - 1))
{
printf("\n5 children created, parent sleeps for 20 secnds...\n");
sleep(2);
for(x = 0 ; x < 5 ; x++)
{
printf("parent thinks pid of child #%d is %d\n", x, childPid[x]); // This is the new line!
int waitValue = waitpid(childPid[x], &status, 0);
printf("waitpid() status: %d\n", status);
printf("waitpid() return value: %d\n", waitValue);
}
exit(0); //dont create too many children
}
}
}
return 0;
}
Compare the output with the output of your child processes (focus on the pid's) and then think about how the children are connected with the parent.
Bye, Andreas