-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_bonus.c
80 lines (74 loc) · 2.42 KB
/
server_bonus.c
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
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* server_bonus.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: lgaudin <[email protected]> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2023/06/09 15:02:13 by lgaudin #+# #+# */
/* Updated: 2023/06/10 14:30:45 by lgaudin ### ########.fr */
/* */
/* ************************************************************************** */
#include "libft/libft.h"
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define END_TRANSMISSION '\0'
/**
* @brief Checks if the signal is SIGUSR1. If it is, it will
* assign 1 to the LSB. Else, it will assign 0 (actually it simply
* won't modify it).
*
* Example:
* 00101100 current_char
* 00000001 result of (sigsent == SIGUSR1)
* --------
* 00101101 result stored in message after the bitwise OR operation
*
* It will then increment the bit index.
* If it is 8, it means that the char has been fully transmitted.
* It will then print it and reset the bit index and the current char.
* Else, it will shift the current char to the left by 1.
*
* @param signal SIGUSR1 or SIGUSR2
*/
void handle_signal(int signal, siginfo_t *info, void *context)
{
static unsigned char current_char;
static int bit_index;
(void)context;
current_char |= (signal == SIGUSR1);
bit_index++;
if (bit_index == 8)
{
if (current_char == END_TRANSMISSION)
ft_printf("\n");
else
ft_printf("%c", current_char);
bit_index = 0;
current_char = 0;
}
else
current_char <<= 1;
if (signal == SIGUSR1)
kill(info->si_pid, SIGUSR1);
else if (signal == SIGUSR2)
kill(info->si_pid, SIGUSR2);
}
/**
* @brief Prints its program's PID and calls the signal handlers.
*/
int main(void)
{
struct sigaction sa;
sa.sa_sigaction = &handle_signal;
sa.sa_flags = SA_SIGINFO;
sigemptyset(&sa.sa_mask);
printf("%d\n", getpid());
sigaction(SIGUSR1, &sa, NULL);
sigaction(SIGUSR2, &sa, NULL);
while (1)
pause();
return (0);
}