C Board  

Go Back   C Board > General Programming Boards > C Programming

Reply
 
LinkBack Thread Tools Display Modes
Old 11-13-2009, 07:26 AM   #1
Registered User
 
Join Date: Mar 2005
Posts: 24
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
Drainy is offline   Reply With Quote
Old 11-13-2009, 10:08 AM   #2
Registered User
 
Join Date: Oct 2006
Location: Canada
Posts: 1,230
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)
}
nadroj is offline   Reply With Quote
Reply

Thread Tools
Display Modes

Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
Fork(), pause(), and storing PID's in a linked list vital101 C Programming 10 09-28-2007 02:16 AM
Fork() not working. BENCHMARKMAN C++ Programming 3 08-01-2007 12:28 AM
Fork - unpredictable? fredkwok Linux Programming 4 03-26-2006 02:49 PM
fork(), exit() - few questions! s3t3c C Programming 10 11-30-2004 06:58 AM
Daemon programming: allocated memory vs. fork() twisgabak Linux Programming 2 09-25-2003 02:53 PM


All times are GMT -6. The time now is 12:53 AM.


Powered by vBulletin® Version 3.8.1
Copyright ©2000 - 2010, Jelsoft Enterprises Ltd.
Search Engine Optimization by vBSEO 3.3.2

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22