69 lines
1.6 KiB
C
69 lines
1.6 KiB
C
#include <stdio.h>
|
|
#include <stdlib.h>
|
|
#include <unistd.h>
|
|
#include <time.h>
|
|
#include <sys/types.h>
|
|
#include <sys/wait.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[]) {
|
|
int i;
|
|
unsigned char arr[SIZE];
|
|
int pipefd[2];
|
|
pid_t pid;
|
|
int found_by_child = 0;
|
|
int found_by_parent;
|
|
|
|
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;
|
|
|
|
if (pipe(pipefd) == -1) {
|
|
perror("pipe");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
pid = fork();
|
|
if (pid == -1) {
|
|
perror("fork");
|
|
exit(EXIT_FAILURE);
|
|
}
|
|
|
|
if (pid == 0) { // Processus fils
|
|
close(pipefd[0]); // Ferme l'entrée du pipe
|
|
int result = search(arr, SIZE / 2, SIZE - 1);
|
|
write(pipefd[1], &result, sizeof(result));
|
|
close(pipefd[1]); // Ferme la sortie du pipe
|
|
exit(EXIT_SUCCESS);
|
|
} else { // Processus père
|
|
close(pipefd[1]); // Ferme la sortie du pipe
|
|
found_by_parent = search(arr, 0, SIZE / 2 - 1);
|
|
read(pipefd[0], &found_by_child, sizeof(found_by_child));
|
|
close(pipefd[0]);
|
|
wait(NULL);
|
|
|
|
if (found_by_parent || found_by_child)
|
|
printf("Found !\n");
|
|
else
|
|
printf("Not found !\n");
|
|
}
|
|
|
|
return EXIT_SUCCESS;
|
|
}
|