summaryrefslogtreecommitdiff
path: root/server.c
blob: 74979702a85b838d4a91cbbfb6f2b58b54c2ef85 (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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   server.c                                           :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: kdx    <kdx   @student.42angouleme.fr      +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2022/10/09 03:37:08 by kdx               #+#    #+#             */
/*   Updated: 2022/10/12 05:32:45 by kdx              ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "libft/libft.h"
#include <unistd.h>
#include <signal.h>

static uint8_t	*g_buffer;

static void	buffer_append(uint8_t byte)
{
	uint8_t	*new_buffer;
	size_t	len;

	if (g_buffer == NULL)
	{
		g_buffer = ft_calloc(2, sizeof(char));
		if (g_buffer == NULL)
			exit(1);
		g_buffer[0] = byte;
	}
	else
	{
		len = ft_strlen((char *)g_buffer);
		new_buffer = ft_calloc(len + 2, sizeof(char));
		if (new_buffer == NULL)
		{
			ft_free(g_buffer);
			exit(1);
		}
		ft_strlcpy((char *)new_buffer, (char *)g_buffer, -1);
		new_buffer[len] = byte;
		ft_free(g_buffer);
		g_buffer = new_buffer;
	}
}

static void	handler(int signum)
{
	static uint8_t	byte;
	static size_t	bit;

	byte |= (signum == SIGUSR2) << bit;
	bit += 1;
	if (bit >= 8)
	{
		if (g_buffer != NULL && byte == 0)
		{
			write(1, g_buffer, ft_strlen((char *)g_buffer));
			ft_free(g_buffer);
			g_buffer = NULL;
		}
		else if (byte != 0)
			buffer_append(byte);
		byte = 0;
		bit = 0;
	}
	return ;
}

static void	sigint_handler(int signum)
{
	(void)signum;
	ft_free(g_buffer);
	exit(0);
}

int	main(void)
{
	pid_t	pid;

	pid = getpid();
	if (signal(SIGUSR1, handler) == SIG_ERR || signal(SIGUSR2, handler))
		return (1);
	if (signal(SIGINT, sigint_handler) == SIG_ERR)
		return (1);
	ft_puti128_fd(pid, 1);
	ft_putchar_fd('\n', 1);
	while (1)
		;
	return (0);
}