BUT2/SCR/TP03/ex5.c

125 lines
2.2 KiB
C
Raw Normal View History

2023-10-12 16:39:49 +02:00
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#define SIZE 1000
int search0(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 search1(const unsigned char * t,int start,int end)
{
int milieu = (end-start)/2;
int pid = fork();
int i;
int status;
if (pid < 0){
return 0;
}
if (pid == 0){
exit(search0(t,start,milieu+1));
}
if (pid > 0){
if (search0(t,milieu+1,end)){
return 1;
}
wait(&status);
return WEXITSTATUS(status);
}
return 0;
}
int search2(const unsigned char * t,int start,int end)
{
int i;
int nbFils;
int taille = (end-start);
int pid;
int status;
printf("Enter a number between 0 and 100: ", SIZE);
scanf(" %d", &nbFils);
for (int i=0; i<nbFils; i++){
pid = fork();
if (pid < 0){
exit(0);
}
if (pid == 0){
exit(search0(t, i*taille/nbFils, (i+1)*taille/nbFils));
}
}
for (int i=0; i<nbFils; i++){
wait(&status);
if (WEXITSTATUS(status) == 1){
return 1;
}
}
return 0;
}
int search3(const unsigned char * t,int start,int end)
{
int i;
int nbFils;
int taille = (end-start);
int pid;
int status;
printf("Enter a number between 0 and 100: ", SIZE);
scanf(" %d", &nbFils);
int* child_pids = (int*) malloc(sizeof(int) * nbFils);
for (int i=0; i<nbFils; i++){
pid = fork();
if (pid < 0){
exit(0);
}
if (pid == 0){
exit(search0(t, i*taille/nbFils, (i+1)*taille/nbFils));
}
child_pids[i] = pid;
}
for (int i=0; i<nbFils; i++){
wait(&status);
if (WEXITSTATUS(status) == 1){
for (int j = 0; j < nbFils; j++) {
kill(child_pids[j], SIGTERM);
}
return 1;
}
}
return 0;
}
int main(int argc , char * argv[])
{
unsigned char arr[SIZE];
int i;
srandom(time(NULL));
for (i = 0; i < SIZE; i++)
arr[i] = (unsigned char) (random() % 255) + 1;
printf("Enter a number between 0 and %d: ", SIZE);
scanf(" %d", &i);
if (i >= 0 && i < SIZE) arr[i] = 0;
if (search3(arr,0,SIZE-1))
printf("Found !\n");
else
printf("Not found !\n");
return EXIT_SUCCESS;
}