-
Notifications
You must be signed in to change notification settings - Fork 0
/
child.c
64 lines (53 loc) · 1.45 KB
/
child.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
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include "io_helper.h"
// Reverses the provided string.
void Reverse(char* buf, size_t len) {
for (size_t i = 0; i < len / 2; ++i) {
char c = buf[i];
buf[i] = buf[len - i - 1];
buf[len - i - 1] = c;
}
}
int main(void) {
int in = fileno(stdin);
int out = fileno(stdout);
fprintf(stderr, "child : Starting\n");
char buf[1024];
do {
// Read message length.
size_t len;
ssize_t sz = ReadFull(in, &len, sizeof(size_t));
if (sz != sizeof(size_t)) {
fprintf(stderr, "child : Failed to read message size.\n");
return 1;
}
if (len > sizeof(buf)) {
fprintf(stderr, "child : Message size too long.\n");
return 1;
}
// Parent tells us to stop by sending 0.
if (len == 0) {
fprintf(stderr, "child : Read quit message\n");
break;
}
// Read message data.
sz = ReadFull(in, buf, len);
if (sz != (ssize_t)len) {
fprintf(stderr, "child : Failed to read message.\n");
return 1;
}
fprintf(stderr, "child : Read message : %.*s\n", (int)len, buf);
// Reverse and send response.
Reverse(buf, len);
fprintf(stderr, "child : Sending response : %.*s\n", (int)len, buf);
sz = WriteFull(out, buf, len);
if (sz != (ssize_t)len) {
fprintf(stderr, "child : Failed to write message.\n");
return 1;
}
} while (1);
fprintf(stderr, "child : Exiting\n");
return 0;
}