aboutsummaryrefslogtreecommitdiff
path: root/philo_three/src/main.c
blob: a6c637091eb2e81fe48a01a863713eb40d9444d5 (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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   main.c                                             :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cacharle <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/15 00:45:24 by cacharle          #+#    #+#             */
/*   Updated: 2020/10/01 09:34:55 by cacharle         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "philo_three.h"

sem_t	*philo_sem_create(char *name, int value)
{
	sem_t	*sem;

	sem_unlink(name);
	sem = sem_open(name, O_CREAT | O_EXCL, 0700, value);
	if (sem == SEM_FAILED)
		return (NULL);
	return (sem);
}

int main(int argc, char **argv)
{
	t_philo_args	args;
	t_philo			philo;
	sem_t			*forks;
	sem_t			*sem_stdout;
	sem_t			*sem_dead;

	if (!parse_args(&args, argc, argv))
		return (1);


	if ((forks = philo_sem_create(PHILO_SEM_NAME, args.philo_num)) == NULL ||
		(sem_stdout = philo_sem_create(PHILO_SEM_STDOUT_NAME, 1)) == NULL ||
		(sem_dead = philo_sem_create(PHILO_SEM_DEAD_NAME, 1)) == NULL)
		return (1);

	pid_t	*pids;
	pids = malloc(sizeof(pid_t) * args.philo_num);

	int i = -1;
	while (++i < args.philo_num)
	{
		philo.conf = &args;
		philo.id = i + 1;
		if ((pids[i] = child_start(&philo)) == -1)
		{
			free(pids);
			return (1);
		}
	}

	sem_wait(sem_dead);
	sem_wait(sem_dead);

	i = -1;
	while (++i < args.philo_num)
		kill(pids[i], SIGKILL);
	free(pids);

	sem_close(forks);
	sem_close(sem_stdout);
	sem_close(sem_dead);
	sem_unlink(PHILO_SEM_NAME);
	sem_unlink(PHILO_SEM_STDOUT_NAME);
	sem_unlink(PHILO_SEM_DEAD_NAME);
	return (0);
}