-
Fork()
Hi,
I am currently having issue with a fork command I am issuing, I am attempting to use fork to create x number of identical processes however it is creating the required amount and then the child appears to enter into the same fork and create another x amount of forks, is there a trick to avoid this? I am using a for loop to increment until I hit the x amount of forks required.
I am not looking for code but just some sort of logical thinking around this problem so I can try and get over this hurdle myself.
Thanks
-
Its hard to understand what your doing without seeing the code. Its been a little while since Ive used "fork", etc, but if your doing something like this
Code:
int i;
for ( i=0; i < MAX; i++ )
{
fork();
childFunction(); // this should never return to here
}
you should do
Code:
int i;
for ( i=0; i < MAX; i++ )
{
if ( fork() == 0 ) // only the child should call the childFunction
{
childFunction(); // this should never return to here
}
}
Also, the key is that "childFunction()" never returns to the calling function. If you have something like
Code:
int childFunction() // whatever return type
{
// do something
return 5; // return something
}
this child process will return to the calling process, and continue its own "version" of the for loop, the child itself creating its own children (recursively). This is obviously a bad thing. As mentioned, you have to make sure this child function never returns, i.e.
Code:
int childFunction() // whatever return type
{
// do something
// kill this process (using kill and getpid()) or simply use an "exit" call so this process ends (exit(0))
return 5; // required by language to return something, even though it never will (because process would have ended on previous line)
}