aboutsummaryrefslogtreecommitdiff
path: root/philo_three/src/child.c
blob: 5bc01291d997e5a66df405a6301f541df2492ac8 (plain)
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
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   child.c                                            :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <me@cacharle.xyz>                 +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/09/30 14:36:16 by cacharle          #+#    #+#             */
/*   Updated: 2020/10/01 09:11:29 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "philo_three.h"

void	*routine_death(t_philo *philo)
{
	t_time	current;

	current = h_time_now();
	while (current - philo->time_last_eat < philo->conf->timeout_death)
		current = h_time_now();
	event_die(philo);
	return (NULL);
}

pid_t	child_start(t_philo *philo)
{
	pid_t		pid;
	pthread_t	thread_death;

	pid = fork();
	if (pid == -1)
		return (-1);
	if (pid == 0)
	{
		philo->forks = sem_open(PHILO_SEM_NAME, 0);
		philo->sem_stdout = sem_open(PHILO_SEM_STDOUT_NAME, 0);
		philo->sem_dead = sem_open(PHILO_SEM_DEAD_NAME, 0);
		philo->time_last_eat = h_time_now();
		pthread_create(&thread_death, NULL, (t_routine)routine_death, philo);
		event_think(philo);
		while (true)
		{
			event_take_fork(philo);
			event_take_fork(philo);
			philo->time_last_eat = h_time_now();
			event_eat(philo);
			event_sleep(philo);
			event_think(philo);
		}
		exit(0);
	}
	return pid;
}