This is a very common problem observed with fork.
You can have some flag variable which will prevent the child process to fork again when the parent forks.
A very primitive code may be somthing like this:-
#include <stdio.h>
#include <unistd.h>
#include <
errno.h>
void main()
{
int child1, child2, val, if_child;
char err[1000];
if_child = 1;
memset(err,'\0',strlen(err));
printf("\nParent process ID is %d \n",getpid());
child1 = fork();
if (child1 == -1)
{
strcpy(err, strerror(
errno));
}
else
{
if(child1 > 0) /* If fork command is successful child PID will be greater than zero. */
{
printf("\nThe child1 process ID is %d \n", child1);
if_child = 0;
/* Set the flag here to prevent child process from forking */
}
}
memset(err,'\0',strlen(err));
if (if_child == 0)
{
child2 = fork();
if (child2 == -1)
{
strcpy(err, strerror(
errno));
}
printf("\nThe child2 process ID is %d \n", child2);
kill(child2);
}
kill(child1);
exit(0);
}