You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.6 KiB

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <unistd.h>
#include <errno.h>
#include <time.h>
#include <sys/wait.h>
int main(int argc, char **argv) {
if (argc != 2) {
fprintf(stderr, "Usage: %s <N>\n", argv[0]);
exit(1);
}
int N = atoi(argv[1]);
if (N <= 0) {
fprintf(stderr, "N doit être un entier positif.\n");
exit(1);
}
pid_t pid;
int etat;
struct timespec t;
int fils_id = 1; // Compteur pour l'identité des fils
for (int i = 1; i <= N; i++) {
switch (pid = fork()) {
case -1:
perror("fork");
exit(errno);
case 0:
printf("[fils %d]: je suis le fils de pid %d\n", fils_id, getpid());
for (int j = 0; j < 10; j++) {
printf("[fils %d]: %d\n", fils_id, j);
t.tv_sec = 0;
t.tv_nsec = i*500000000;
nanosleep(&t, NULL);
}
system("ps -f");
exit(2);
default:
fils_id++; // Incrémente le compteur pour le prochain fils
break;
}
}
for (int i = 0; i < N; i++) {
if ((pid = wait(&etat)) == -1) {
perror("pb avec le wait");
exit(errno);
}
if (WIFEXITED(etat))
printf("[pere]: mon fils %d a retourne le code %d\n", pid, WEXITSTATUS(etat));
else
printf("[pere]: mon fils %d s est mal termine\n", pid);
}
printf("[pere]: Fin du processus pere de pid %d.\n", getpid());
exit(0);
}