Here is another one, using a guard and separating out the child code.
Somehow, I feel this one can be easier to read in some situations.
Especially with the requirement that all control stay in the parent.
/*
bla, bla, code example, bla, bla, freely distributed, bla.
(C) Jan Atle Ramsli, Bug producer extraordinaire, esq.
trollet@skynet.be
*/
#include <unistd.h>
#include <stdio.h>
/* A static variable will only be 0 when the parent is loaded */
pid_t statpid = 0;
child_stuff()
{
printf("\tI am a child\n");
for (;
{
}
}
main(int ac, char *av[])
{
int i, num;
pid_t mypid;
pid_t children[100];
num = atoi(av[1]);
if(num < 1 || num > 99)
num = 10;
mypid = getpid();
printf("Hi, I am %d\n", mypid);
/*
* First time : statpid = 0, mypid = 0xef
* Other times: statpid = 0xef, mypid = 0xef+x
* where x != 0
* I think it makes the code clearer if the flag is show here,
* documented here, and acted upon here.
*/
if (statpid != 0)
{
child_stuff();
exit(0); /* You may or may not get here */
}
/*
* We are adult now, so we can allow ourselves to have
* children.
*/
for (i = 0; i < atoi(av[1]); i++)
{
if (! statpid)
{
switch(fork())
{
case 0:
statpid = getpid(); /* Note that we have had a child */
printf("Giving birth to child nr. %d is a wonderful thing\n", i+1);
break;
default:
printf("Uووووووووh, buuu-ووووh!\n");
break;
}
}
}
/*
* WE set it here, too :-]
*/
statpid = getpid();
}