Multiple child process

israkir picture israkir · May 18, 2009 · Viewed 94.7k times · Source

can someone help me about how to create multiple child processes which have the same parent in order to do "some" part of particular job?

for example, an external sorting algorithm which is applied with child processes; each child process sorts a part of data and finally the parent merges them..

EDIT: Maybe I should mention the forking multiple child processes with loop..

Answer

pts picture pts · May 18, 2009

Here is how to fork 10 children and wait for them to finish:

pid_t pids[10];
int i;
int n = 10;

/* Start children. */
for (i = 0; i < n; ++i) {
  if ((pids[i] = fork()) < 0) {
    perror("fork");
    abort();
  } else if (pids[i] == 0) {
    DoWorkInChild();
    exit(0);
  }
}

/* Wait for children to exit. */
int status;
pid_t pid;
while (n > 0) {
  pid = wait(&status);
  printf("Child with PID %ld exited with status 0x%x.\n", (long)pid, status);
  --n;  // TODO(pts): Remove pid from the pids array.
}