Thread: Fork()

  1. #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

  2. #2
    Registered User
    Join Date
    Oct 2006
    Location
    Canada
    Posts
    1,243
    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)
    }

Popular pages Recent additions subscribe to a feed

Similar Threads

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