Beispiellösung

Content

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

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

/* return real time in seconds since some arbitrary point in the past */
double walltime() {
   static int ticks_per_second = 0;
   if (!ticks_per_second) {
      ticks_per_second = sysconf(_SC_CLK_TCK);
   }
   struct tms timebuf;
   /* times returns the number of real time ticks passed since some
      arbitrary point in the past */
   return (double) times(&timebuf) / ticks_per_second;
}

int main() {
   double t0 = walltime();
   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);
      }
   }

   double t1 = walltime() - t0;
   printf("fork & wait per process: %.4lf us\n", t1*1000*1000 / N);
}

Es wird hier _exit benutzt, damit das Leeren der Puffer der stdio im Kindprozess unterbleibt.

Übersetzung und Ausführung

heim$ gcc -Wall -o timed-forkandwait timed-forkandwait.c
heim$ ./timed-forkandwait
fork & wait per process: 30.0000 us
heim$