-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathecho-client.c
More file actions
96 lines (83 loc) · 2.22 KB
/
Copy pathecho-client.c
File metadata and controls
96 lines (83 loc) · 2.22 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
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdbool.h>
#include <signal.h>
#include <errno.h>
#define FIFO_PATH "/tmp/echo_fifo"
#define BUFFER_SIZE 1024
bool running = true;
static void handle_terminate(int signal) {
running = false;
}
int main(int argc, char **argv) {
struct sigaction sa_term;
sa_term.sa_handler = handle_terminate;
sigemptyset(&sa_term.sa_mask);
sa_term.sa_flags = 0;
if (sigaction(SIGTERM, &sa_term, NULL) == -1) {
perror("sigaction SIGTERM");
exit(EXIT_FAILURE);
}
if (sigaction(SIGINT, &sa_term, NULL) == -1) {
perror("sigaction SIGINT");
exit(EXIT_FAILURE);
}
if (sigaction(SIGQUIT, &sa_term, NULL) == -1) {
perror("sigaction SIGQUIT");
exit(EXIT_FAILURE);
}
bool descret;
if (argc > 1) {
if (strcmp(argv[1], "-descret") == 0) {
descret = true;
}
}
int fifo_fd = open(FIFO_PATH, O_WRONLY);
if (fifo_fd == -1) {
perror("open FIFO for writing");
exit(EXIT_FAILURE);
}
char buffer[BUFFER_SIZE];
printf("Echo client. Please enter messages (Ctrl+C to exit):\n");
while (running) {
int res = 0;
do {
res = fgets(buffer, BUFFER_SIZE, stdin)!=0;
if (!running) {
if (close(fifo_fd) == -1) {
perror("close");
}
exit(0);
}
} while (res == 0 && errno == EINTR);
if(res == 0){
printf("closing\n");
break;
}
size_t len = strlen(buffer);
if (buffer[len - 1] == '\n')
buffer[len - 1] = '\0';
if (write(fifo_fd, buffer, strlen(buffer)) == -1) {
perror("write");
break;
}
if (descret) {
if (close(fifo_fd) == -1) {
perror("close");
break;
}
fifo_fd = open(FIFO_PATH, O_WRONLY);
if (fifo_fd == -1) {
perror("open FIFO for writing");
exit(EXIT_FAILURE);
}
}
}
if (close(fifo_fd) == -1) {
perror("close");
}
return 0;
}