tkt
This commit is contained in:
83
SCR3.1/TP3/Exo5/v2.c
Normal file
83
SCR3.1/TP3/Exo5/v2.c
Normal file
@@ -0,0 +1,83 @@
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <unistd.h>
|
||||
#include <time.h>
|
||||
#include <sys/types.h>
|
||||
#include <sys/wait.h>
|
||||
#include <string.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 pid;
|
||||
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++) {
|
||||
pid = fork();
|
||||
if (pid == -1) {
|
||||
perror("fork");
|
||||
exit(EXIT_FAILURE);
|
||||
}
|
||||
|
||||
if (pid == 0) { // Processus fils
|
||||
int start = i * chunk_size;
|
||||
int end = start + chunk_size - 1;
|
||||
if (i == n_procs - 1) { // Le dernier fils gère le reste
|
||||
end += remainder;
|
||||
}
|
||||
int result = search(arr, start, end);
|
||||
exit(result);
|
||||
}
|
||||
}
|
||||
|
||||
for (i = 0; i < n_procs; i++) {
|
||||
waitpid(-1, &status, 0);
|
||||
if (WIFEXITED(status)) {
|
||||
if (WEXITSTATUS(status) == 1) {
|
||||
found = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (found)
|
||||
printf("Found !\n");
|
||||
else
|
||||
printf("Not found !\n");
|
||||
|
||||
return EXIT_SUCCESS;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user