#include #include #include #include #include main() { int status; int mx, i, n, running, p[2]; fd_set master, copy; FD_ZERO(&master); FD_SET(0, &master); mx = 0; running = 0; n = 0; while (1) { memcpy(©, &master, sizeof(fd_set)); select(mx+1, ©, NULL, NULL, NULL); if (FD_ISSET(0, ©)) { /* Read from stdin. Fork off processes later. */ if (scanf("%d", &n) != 1 || n <= 0) exit(0); } for (i = 1; i <= mx; i++) { /* If a child is dead, call wait() */ if (FD_ISSET(i, ©)) { wait(&status); FD_CLR(i, &master); close(i); running--; } } while (running < n) { /* Now fork off children if necessary. */ pipe(p); /* Set up the pipe */ FD_SET(p[0], &master); if (p[0] > mx) mx = p[0]; if (fork() == 0) { /* Close all unnecessary fd's in the child */ for (i = 0; i <= mx; i++) { if (FD_ISSET(i, &master)) close(i); } execlp("experiment", "experiment", NULL); exit(1); } close(p[1]); /* Close the write end in the parent */ running++; } } }