diff options
Diffstat (limited to 'server.c')
-rw-r--r-- | server.c | 91 |
1 files changed, 91 insertions, 0 deletions
diff --git a/server.c b/server.c new file mode 100644 index 0000000..7497970 --- /dev/null +++ b/server.c @@ -0,0 +1,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); +} |