1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57
| #include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MAX_CHILDREN 5
#define MAX_PROCESS 10
#define SLEEP 5
int main()
{
int children = 0;
int process = 0;
pid_t pid;
while (process < MAX_PROCESS) {
if (children < MAX_CHILDREN) {
pid = fork();
if (pid < 0) {
perror("fork");
exit(EXIT_FAILURE);
} else if (!pid) {
pid = getpid();
printf("%u: Début du fils...\n", pid);
sleep(SLEEP);
printf("%u: Fin du fils.\n", pid);
exit(EXIT_SUCCESS);
}
++children;
++process;
printf("%u: Lancement du fils %u (%d/%d - %d/%d)...\n", getpid(), pid, process, MAX_PROCESS, children, MAX_CHILDREN);
} else {
pid = wait(NULL);
--children;
printf("%u: Fin du fils %u (%d/%d - %d/%d).\n", getpid(), pid, process, MAX_PROCESS, children, MAX_CHILDREN);
}
}
while (children > 0) {
pid = wait(NULL);
--children;
printf("%u: Fin du fils %u (%d/%d - %d/%d).\n", getpid(), pid, process, MAX_PROCESS, children, MAX_CHILDREN);
}
return EXIT_SUCCESS;
} |
Partager