#include #include #include #include double drandom(void) { return (double)random() / 2147483648.0; } int main(int argc, char **argv) { long inside, rounds, truerounds, childinside, childrounds; long i; double x, y; unsigned seed = 12345; int j; int children; int child; int (*cpipe)[2]; int *cpid; if (argc < 3 || 1!= sscanf(argv[1], "%ld", &rounds)) { fprintf(stderr,"Usage: %s rounds seed [seed...]\n", argv[0]); return 1; } children = argc - 2; cpipe = malloc(2*children*sizeof(int)); cpid = malloc(children*sizeof(int)); for (j = 2; j < argc; j++) { if (1!=sscanf(argv[j],"%u", &seed)) { fprintf(stderr, "invalid seed '%s'\n", argv[j]); return 1; } child = j-2; childrounds = rounds / (children - child); rounds -= childrounds; printf("starting child %d with seed %s\n", child, argv[j]); if (pipe(cpipe[child])) { perror("pipe"); return 1; } if (!(cpid[child] = fork())) { close(cpipe[child][0]); srandom(seed); inside = 0; i = childrounds; while (i--) { x = drandom(); y = drandom(); if (x*x + y*y < 1) inside++; } write(cpipe[child][1],&inside,sizeof(inside)); write(cpipe[child][1],&childrounds,sizeof(childrounds)); close(cpipe[child][1]); return 0; } else if (cpid[child] < 0) { perror("fork"); return 0; } close(cpipe[child][1]); } inside = 0; truerounds = 0; for (child = 0; child < children; child++) { waitpid(cpid[child],NULL,0); read(cpipe[child][0],&childinside,sizeof(childinside)); read(cpipe[child][0],&childrounds,sizeof(childrounds)); close(cpipe[child][0]); printf("child %d reported %ld:%ld -> %f\n", child, childinside, childrounds, (double)childinside/childrounds * 4); inside += childinside; truerounds += childrounds; } printf("Total: %ld:%ld -> %f\n", inside, truerounds, (double)inside/truerounds * 4); return 0; }