Beispiellösung

Content

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

#define N 10 /* number of child processes */

int main() {
   for (int i = 1; i <= N; ++i) {
      pid_t child = fork();
      if (child == -1) {
	 perror("unable to fork"); exit(1);
      }
      if (child == 0) {
	 /* child process */
	 _exit(i);
      }
   }

   /* parent process */
   pid_t child; int stat; int sum = 0;
   while ((child = wait(&stat)) >= 0) {
      if (WIFEXITED(stat)) {
	 sum += WEXITSTATUS(stat);
      } else {
	 printf("child %d terminated abnormally\n", (int) child);
      }
   }
   printf("sum = %d\n", sum);
}

Übersetzung und Ausführung

heim$ gcc -Wall -o forkandwait10 forkandwait10.c
heim$ ./forkandwait10
sum = 55
heim$