-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient.c
More file actions
112 lines (102 loc) · 2.47 KB
/
Copy pathclient.c
File metadata and controls
112 lines (102 loc) · 2.47 KB
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
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
/* ************************************************************************** */
/* */
/* ::: :::::::: */
/* client.c :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: kenakamu <kenakamu@student.42tokyo.jp> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2025/09/09 14:09:31 by kenakamu #+# #+# */
/* Updated: 2025/09/28 22:25:48 by kenakamu ### ########.fr */
/* */
/* ************************************************************************** */
#include "minitalk.h"
static int wait_for_server_response(unsigned char *c_ptr)
{
int timeout_counter;
timeout_counter = 0;
while (!g_server_act && timeout_counter < 5000)
{
usleep(10);
timeout_counter++;
}
if (!g_server_act)
{
write(STDERR_FILENO, "Error: Server response timeout\n", 32);
return (-1);
}
*c_ptr = *c_ptr >> 1;
return (0);
}
static int send_char_bits(pid_t pid, unsigned char c)
{
size_t n;
int signal;
n = 8;
while (n--)
{
g_server_act = 0;
if (!(c & 1))
signal = SIGUSR1;
else
signal = SIGUSR2;
if (kill(pid, signal) == -1)
{
write(STDERR_FILENO, "Error: Failed to send signal\n", 30);
return (-1);
}
if (wait_for_server_response(&c) == -1)
return (-1);
}
return (0);
}
int client(pid_t pid, char *str)
{
size_t i;
struct sigaction sa;
setup_sigaction(&sa, client_task_end_handler);
sigaction(SIGUSR1, &sa, NULL);
i = 0;
while (str[i])
{
if (send_char_bits(pid, str[i]) == -1)
return (-1);
i++;
}
if (send_char_bits(pid, '\n') == -1)
return (-1);
return (0);
}
static int validate_and_run_client(const char *pid_str, char *content)
{
int i;
pid_t pid;
i = 0;
while (pid_str[i])
{
if (ft_isdigit(pid_str[i]) == false)
{
write(STDERR_FILENO, "Error\n", 6);
return (-1);
}
i++;
}
pid = (pid_t)ft_atoi(pid_str);
if (pid <= 0)
{
write(STDERR_FILENO, "Error\n", 6);
return (-1);
}
if (client(pid, content) == -1)
return (-1);
return (0);
}
int main(int arc, char **arv)
{
if (arc == 3)
return (validate_and_run_client(arv[1], arv[2]));
else
{
write(STDERR_FILENO, "Error\n", 6);
return (-1);
}
}