Creating Multiple Processes

I am having problems creating multiple forks. I want create a certain number of forks, each call a program and each wait for a different value. How is this accomplished my loop is not doing the trick.

for (i = 0; i < 5; i++) {

        if (fork() < 0) {
            //print error
        }

        else if (fork() == 0) {
            //run a program (exec(...)
        }

        else {
            p_id = wait(&result);
        }
    }

I know how to use the wait() and exec() call but can't figure out how to do this for multiple forks I need each fork to return a differnt value.

Any help much appreciated.

fork() returns the PID of the child process to the parent, just store its value. Or if you need the value in the child, get it with getpid().

Is the fork at the top of the loop just to run two processes? If so, keep in mind you'll end up with two waiters, too! I usually encapsulate each fork in code like:

pid_t pid=fork();
if(pid < 0)
{
  // error
}
else if(pid == 0)
{
  // child code
  exit(0); // to prevent it executing code below.  after all what if exec fails?
}
else if(pid > 0)
{
  // parent code.
}

My goal is to simply use system calls to add a group of numbers. I retrieve the result through wait(&value) aka the suicide note. So if I had 8 numbers, I first need to create 4 forks, call on a program which returns the sum. I am having problems with the loop the manages this task.

You can only communicate numbers 0 to 255 through a return value, you should know.

#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>

int main(void)
{
  int total=0;
  int n;

  for(n=0; n<4; n++)
  {
      pid_t pid=fork();
      if(pid == 0)  // This code is executed in the child
        return(42); // the child returns from main, stopping execution

    // The parent continues looping.
  }

  for(n=0; n<4; n++)
  {
    int status;
    wait(&status);
    total += WEXITSTATUS(status);
  }

  printf("The total is %d\n", total);
  return(0);
}