/* ************************************************************************** */ /* */ /* .--. _ */ /* init.c |o_o || | */ /* |:_/ || |_ _ ___ __ */ /* By: houtworm // \ \ __| | | \ \/ / */ /* (| | )|_| |_| |> < */ /* Created: 2023/03/15 02:00:19 by houtworm /'\_ _/`\__|\__,_/_/\_\ */ /* Updated: 2023/05/24 02:14:22 by djonker \___)=(___/ */ /* */ /* ************************************************************************** */ #include "../philo.h" int ft_charactercheck(int argc, char **argv) { int i; int j; i = 1; j = 0; while (i < argc) { while (argv[i][j] != '\0') { if (argv[i][j] < '0' || argv[i][j] > '9') return (1); j++; } i++; j = 0; } return (0); } t_strct *ft_parseandvalidateinput(int argc, char **argv) { t_strct *strct; strct = malloc(sizeof(t_strct)); strct->error = NULL; if (ft_charactercheck(argc, argv)) strct->error = "input can only be numbers"; strct->philos = philo_atoi(argv[1]); if (strct->philos < 1 || strct->philos > 500) strct->error = "Min 1 and Max 500 philosophers"; strct->dietime = philo_atoi(argv[2]); if (strct->dietime < 50) strct->error = "die time must be a minimum of 50ms"; strct->eattime = philo_atoi(argv[3]); if (strct->eattime < 50) strct->error = "eat time must be a minimum of 50ms"; strct->sleeptime = philo_atoi(argv[4]); if (strct->sleeptime < 50) strct->error = "sleeptime must be a minimum of 50ms"; if (argc == 6) strct->target = philo_atoi(argv[5]); else strct->target = 1000000000; if (strct->target < 0) strct->error = "We can't do negative cycles"; return (strct); } int ft_restoresemaphore(t_strct *strct) { sem_close(strct->dead); sem_close(strct->done); sem_close(strct->hold); sem_close(strct->forks); sem_close(strct->print); sem_unlink("dead"); sem_unlink("done"); sem_unlink("hold"); sem_unlink("forks"); sem_unlink("print"); strct->dead = sem_open("dead", O_CREAT | O_EXCL, 0666, 0); strct->done = sem_open("done", O_CREAT | O_EXCL, 0666, 0); strct->hold = sem_open("hold", O_CREAT | O_EXCL, 0666, 0); strct->print = sem_open("print", O_CREAT | O_EXCL, 0666, 1); strct->forks = sem_open("forks", O_CREAT | O_EXCL, 0666, strct->philos); return (0); } int ft_initstructandmutex(t_strct *strct, int i) { ft_restoresemaphore(strct); strct->alive = 1; while (i <= strct->philos) { strct->philo[i].id = i + 1; strct->philo[i].cycles = 0; strct->philo[i].dietime = &strct->dietime; strct->philo[i].eattime = &strct->eattime; strct->philo[i].sleeptime = &strct->sleeptime; strct->philo[i].strtt = &strct->strtt; strct->philo[i].philos = &strct->philos; strct->philo[i].target = &strct->target; strct->philo[i].alive = &strct->alive; strct->philo[i].forks = strct->forks; strct->philo[i].done = strct->done; strct->philo[i].dead = strct->dead; strct->philo[i].hold = strct->hold; strct->philo[i].print = strct->print; strct->philo[i].pid = strct->pid; i++; } return (0); } void ft_safeprint(t_philo *ps, char *str) { sem_wait(ps->print); if (*ps->alive) printf("%lld %d %s\n", ft_time() - *ps->strtt, ps->id, str); sem_post(ps->print); }