1#include <stdio.h>
2#include <string.h>
3#include <stdlib.h>
4
5#include <errno.h>
6#include <unistd.h>
7
8static size_t r(char* buf, size_t buf_size) {
9  ssize_t read_count;
10  do
11    read_count = read(0, buf, buf_size);
12  while (read_count < 0 && errno == EINTR);
13  if (read_count <= 0)
14    abort();
15  return (size_t)read_count;
16}
17
18static void w(const char* buf, size_t count) {
19  const char* end = buf + count;
20
21  while (buf < end) {
22    ssize_t write_count;
23    do
24      write_count = write(1, buf, count);
25    while (write_count < 0 && errno == EINTR);
26    if (write_count <= 0)
27      abort();
28    buf += write_count;
29  }
30
31  fprintf(stderr, "%zu", count);
32  fflush(stderr);
33}
34
35int main(void) {
36  w("0", 1);
37
38  while (1) {
39    char buf[256];
40    size_t read_count = r(buf, sizeof(buf));
41    // The JS part (test-child-process-stdio-overlapped.js) only writes the
42    // "exit" string when the buffer is empty, so the read is guaranteed to be
43    // atomic due to it being less than PIPE_BUF.
44    if (!strncmp(buf, "exit", read_count)) {
45      break;
46    }
47    w(buf, read_count);
48  }
49
50  return 0;
51}
52