-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
119 lines (110 loc) · 2.94 KB
/
main.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: oabdelka <oabdelka@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/12/09 14:17:44 by oabdelka #+# #+# */
/* Updated: 2024/12/09 14:17:44 by oabdelka ### ########.fr */
/* */
/* ************************************************************************** */
#include "philosopher.h"
static int validate_argument(int value, int index)
{
if (index == 1 && value > 200)
return (printf("max %d\n", 200), 0);
if (index == 5)
{
if (value == -1)
return (1);
if (value < 1 && value != -1)
return (printf("over 1 meal\n"), 0);
}
return (1);
}
/**
(sim) Pointer to the simulation structure.
*/
static int parse_arguments(int ac, t_simulation *simulation, char **av)
{
simulation->num_philosophers = ft_atoi(av[1]);
simulation->time_to_die = ft_atoi(av[2]);
simulation->time_to_eat = ft_atoi(av[3]);
simulation->time_to_sleep = ft_atoi(av[4]);
simulation->end = 0;
simulation->died = 0;
simulation->meals_required = -1;
if (ac == 6)
simulation->meals_required = ft_atoi(av[5]);
return (1);
}
static int validate_inputs(int ac, char **av)
{
int i;
int value;
i = 1;
while (i < ac)
{
value = ft_atoi(av[i]);
if (validate_argument(value, i))
{
if (value <= 0 && !(i == 5 && value == -1))
{
printf("incorrect value: %s !\n", av[i]);
return (0);
}
}
else
return (0);
i++;
}
return (1);
}
static int validate_number_of_arguments(int ac, char **av)
{
int i;
int j;
i = 1;
if (ac != 5 && ac != 6)
{
printf("Usage: ./philo number_of_philosophers time_to_die "
"time_to_eat time_to_sleep [meals_required]\n");
return (0);
}
while (i < ac)
{
j = 0;
while (av[i][j])
{
if (av[i][j] > '9' || av[i][j] < '0')
return (printf("Invalid input: %s\n", av[i]), 0);
j++;
}
i++;
}
return (1);
}
int main(int ac, char **av)
{
t_simulation simulation;
if (!validate_number_of_arguments(ac, av))
return (1);
if (!validate_inputs(ac, av))
return (1);
if (!parse_arguments(ac, &simulation, av))
return (1);
if (!initialize_philosophers(&simulation))
{
destroy_mutexes(&simulation);
return (1);
}
if (!init_mutexes(&simulation))
{
destroy_mutexes(&simulation);
return (1);
}
launch_simulation(&simulation);
terminate_simulation(&simulation);
return (0);
}