/* By: ljiriste <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/03/22 11:19:48 by ljiriste #+# #+# */
-/* Updated: 2024/05/30 11:41:40 by ljiriste ### ########.fr */
+/* Updated: 2024/05/30 12:05:00 by ljiriste ### ########.fr */
/* */
/* ************************************************************************** */
#include <sys/types.h>
#include <signal.h>
-static int seat_philosophers(t_settings *settings, pid_t *philo_pids)
+static int seat_philosophers(t_settings *settings, pid_t *philo_pids, t_sems *semaphores)
{
t_philo philo;
philo_pids[philo.id - 1] = fork();
if (philo_pids[philo.id - 1] == 0)
{
+ close_semaphores(semaphores);
free(philo_pids);
be_a_philosopher(&philo);
}
cleanup(philo_pids, &semaphores);
return (2);
}
- if (seat_philosophers(&settings, philo_pids))
+ if (seat_philosophers(&settings, philo_pids, &semaphores))
{
kill_philosophers(settings.philo_count, philo_pids);
cleanup(philo_pids, &semaphores);
/* By: ljiriste <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 08:45:21 by ljiriste #+# #+# */
-/* Updated: 2024/05/30 11:40:22 by ljiriste ### ########.fr */
+/* Updated: 2024/05/30 12:08:48 by ljiriste ### ########.fr */
/* */
/* ************************************************************************** */
{
char *sem_name;
+ sem_name = create_philo_sem_name(philo->id);
+ if (!sem_name)
+ return (NULL);
+ philo->philo_sem = sem_open(sem_name, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 1);
philo->semaphores.forks = sem_open(FORKS_SEM, 0);
philo->semaphores.fed = sem_open(WELL_FED_SEM, 0);
philo->semaphores.death = sem_open(DEATH_SEM, 0);
philo->semaphores.term = sem_open(TERM_SEM, 0);
philo->semaphores.end = sem_open(END_SEM, 0);
- sem_name = create_philo_sem_name(philo->id);
- if (!sem_name)
- return (NULL);
- philo->philo_sem = sem_open(sem_name, O_CREAT | O_EXCL, S_IRUSR | S_IWUSR, 1);
- if (philo->philo_sem == SEM_FAILED)
+ if (philo->philo_sem == SEM_FAILED
+ || philo->semaphores.forks == SEM_FAILED
+ || philo->semaphores.fed == SEM_FAILED
+ || philo->semaphores.death == SEM_FAILED
+ || philo->semaphores.term == SEM_FAILED
+ || philo->semaphores.end == SEM_FAILED)
{
- sem_wait(philo->semaphores.term);
- printf("An error has occured.\n");
- sem_wait(philo->semaphores.death);
free(sem_name);
return (NULL);
}
return ;
}
+static void error_exit(t_philo *philo, int exit_code)
+{
+ sem_wait(philo->semaphores.term);
+ printf("An error as occured.\n");
+ sem_post(philo->semaphores.death);
+ sem_post(philo->semaphores.end);
+ close_semaphores(&philo->semaphores);
+ exit(exit_code);
+}
+
void be_a_philosopher(t_philo *philo)
{
pthread_t watchers[2];
philo_sem_name = open_semaphores(philo);
if (!philo_sem_name)
- exit(2);
+ error_exit(philo, 2);
if (create_watchers(philo, watchers))
- exit(3);
+ {
+ sem_unlink(philo_sem_name);
+ free(philo_sem_name);
+ error_exit(philo, 3);
+ }
while (is_alive(philo))
{
philo_think(philo);