97 lines
2.3 KiB
C
97 lines
2.3 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <time.h>
|
|
#include <sys/types.h>
|
|
#include <sys/wait.h>
|
|
#include <string.h>
|
|
#include <signal.h>
|
|
|
|
#define SIZE 1000
|
|
|
|
int search(const unsigned char *t, int start, int end) {
|
|
int i;
|
|
for (i = start; i <= end; i++) {
|
|
if (t[i] == 0) {
|
|
return 1;
|
|
}
|
|
}
|
|
return 0;
|
|
}
|
|
|
|
int main(int argc, char *argv[]) {
|
|
if (argc != 2) {
|
|
fprintf(stderr, "Usage: %s <number_of_processes>\n", argv[0]);
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
int n_procs = atoi(argv[1]);
|
|
if (n_procs < 1 || n_procs > 100) {
|
|
fprintf(stderr, "Number of processes must be between 1 and 100.\n");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
int i, status;
|
|
unsigned char arr[SIZE];
|
|
pid_t pids[n_procs];
|
|
int found = 0;
|
|
int chunk_size = SIZE / n_procs;
|
|
int remainder = SIZE % n_procs;
|
|
|
|
srandom(time(NULL));
|
|
|
|
for (i = 0; i < SIZE; i++)
|
|
arr[i] = (unsigned char)(random() % 255) + 1;
|
|
|
|
printf("Entrez un nombre entre 0 et %d: ", SIZE - 1);
|
|
scanf(" %d", &i);
|
|
if (i >= 0 && i < SIZE) arr[i] = 0;
|
|
|
|
for (i = 0; i < n_procs; i++) {
|
|
pids[i] = fork();
|
|
if (pids[i] == -1) {
|
|
perror("fork");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
if (pids[i] == 0) { // Processus fils
|
|
int start = i * chunk_size;
|
|
int end = start + chunk_size - 1;
|
|
if (i == n_procs - 1) {
|
|
end += remainder;
|
|
}
|
|
int result = search(arr, start, end);
|
|
exit(result);
|
|
}
|
|
}
|
|
|
|
for (i = 0; i < n_procs; i++) {
|
|
pid_t pid = waitpid(-1, &status, 0);
|
|
if (pid == -1) {
|
|
perror("waitpid");
|
|
continue;
|
|
}
|
|
|
|
if (WIFEXITED(status) && WEXITSTATUS(status) == 1) {
|
|
found = 1;
|
|
printf("Zéro trouvé ! Envoi de SIGTERM aux autres processus...\n");
|
|
for (int j = 0; j < n_procs; j++) {
|
|
if (pids[j] != 0 && pids[j] != pid) {
|
|
kill(pids[j], SIGTERM);
|
|
}
|
|
}
|
|
break; // Sort de la boucle une fois le zéro trouvé
|
|
}
|
|
}
|
|
|
|
// Attendre la fin des processus restants (ceux tués par SIGTERM)
|
|
while (wait(NULL) > 0);
|
|
|
|
if (found)
|
|
printf("Found !\n");
|
|
else
|
|
printf("Not found !\n");
|
|
|
|
return EXIT_SUCCESS;
|
|
}
|