/* By: ljiriste <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/03/22 11:19:48 by ljiriste #+# #+# */
-/* Updated: 2024/05/30 12:05:00 by ljiriste ### ########.fr */
+/* Updated: 2024/05/30 12:46:31 by ljiriste ### ########.fr */
/* */
/* ************************************************************************** */
{
sem_wait(semaphores->end);
sem_post(semaphores->fed);
+ sem_post(semaphores->forks);
--philo_count;
}
sem_post(semaphores->term);
/* By: ljiriste <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2024/05/09 08:45:21 by ljiriste #+# #+# */
-/* Updated: 2024/05/30 12:08:48 by ljiriste ### ########.fr */
+/* Updated: 2024/05/30 12:49:14 by ljiriste ### ########.fr */
/* */
/* ************************************************************************** */
#include <stdio.h>
#include <stdlib.h>
-static char *open_semaphores(t_philo *philo)
+static int open_semaphores(t_philo *philo)
{
- 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->philo_sem_name = create_philo_sem_name(philo->id);
+ if (!philo->philo_sem_name)
+ return (1);
+ philo->philo_sem = sem_open(philo->philo_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.death == SEM_FAILED
|| philo->semaphores.term == SEM_FAILED
|| philo->semaphores.end == SEM_FAILED)
- {
- free(sem_name);
- return (NULL);
- }
- return (sem_name);
+ return (2);
+ philo->semaphores.check_end = NULL;
+ return (0);
}
static void philo_think(t_philo *philo)
return ;
}
+static void clear_philo(t_philo *philo)
+{
+ close_semaphores(&philo->semaphores);
+ if (philo->philo_sem_name && philo->philo_sem != SEM_FAILED)
+ {
+ sem_close(philo->philo_sem);
+ sem_unlink(philo->philo_sem_name);
+ }
+ free(philo->philo_sem_name);
+ 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);
+ clear_philo(philo);
exit(exit_code);
}
void be_a_philosopher(t_philo *philo)
{
pthread_t watchers[2];
- char *philo_sem_name;
- philo_sem_name = open_semaphores(philo);
- if (!philo_sem_name)
+ if (open_semaphores(philo))
error_exit(philo, 2);
if (create_watchers(philo, watchers))
- {
- sem_unlink(philo_sem_name);
- free(philo_sem_name);
error_exit(philo, 3);
- }
while (is_alive(philo))
{
philo_think(philo);
philo_sleep(philo);
}
destroy_watchers(watchers);
- close_semaphores(&philo->semaphores);
- sem_unlink(philo_sem_name);
- free(philo_sem_name);
+ clear_philo(philo);
exit(0);
}