42_minitalk/server_src/main.c
Camille Chauvet 3b80be7c0f ca parait bon
2023-01-23 14:13:48 +01:00

86 lines
2.1 KiB
C

/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* main.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: cchauvet <cchauvet@student.42angouleme.fr +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/01/20 15:19:31 by cchauvet #+# #+# */
/* Updated: 2023/01/20 17:22:03 by cchauvet ### ########.fr */
/* */
/* ************************************************************************** */
#include <signal.h>
#include <sys/types.h>
#include <unistd.h>
#include "../libftx/libftx.h"
char *ft_tab_int_to_str(int *tab, size_t len)
{
char *str;
size_t i;
str = ft_calloc(len / (sizeof(char) * 8) + 1, sizeof(char));
i = 0;
while (i < len)
{
str[i / (sizeof(char) * 8)] = str[i / (sizeof(char) * 8)] * 2 + tab[i];
i++;
}
return (str);
}
int ft_is_finished(int *tab, size_t len)
{
size_t i;
unsigned long sum;
if (len >= sizeof(char) * 8 && (len % (sizeof(char) * 8)) == 0)
{
sum = 0;
i = len - sizeof(char) * 8;
while (i < len)
{
sum += tab[i];
i++;
}
return (sum == 0);
}
return (0);
}
void handler(int num)
{
static int *tab = NULL;
static size_t len = 0;
char *str;
tab = ft_realloc(tab, len, len + 2, sizeof(int));
if (tab == NULL)
return ;
if (len == 0)
tab[0] = num;
else
tab[len] = num == tab[0];
ft_printf("tab[%d] = %d\n", len, tab[len]);
len++;
if (ft_is_finished(tab + 1, len - 1))
{
str = ft_tab_int_to_str(tab + 1, len - 1);
free(tab);
ft_printf("%s\n", str);
free(str);
tab = NULL;
len = 0;
}
}
int main(void)
{
signal(SIGUSR1, handler);
signal(SIGUSR2, handler);
ft_printf("PID: %d\n", getpid());
while (1)
;
}