The UNIX and Linux Forums  

Go Back   The UNIX and Linux Forums > Top Forums > High Level Programming
.
google unix.com




View Single Post in the UNIX and Linux Forums - Click on the Thread or Permalink to View Entire Thread -->
  #2 (permalink)  
Old 01-22-2002
aniruddha aniruddha is offline
Registered User
  
 

Join Date: Jan 2002
Location: Pune, India
Posts: 3
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);
}