1// SPDX-License-Identifier: GPL-3.0-or-later
2
3#include <errno.h>
4#include <mos/mos_global.h>
5#include <mos/tasks/signal_types.h>
6#include <mos/types.h>
7#include <signal.h>
8#include <stdio.h>
9#include <stdlib.h>
10#include <string.h>
11#include <unistd.h>
12
13void badbadbad(void)
14{
15 puts(string: "badbadbad");
16 abort();
17}
18
19static const char *data = "Hello, world!";
20
21static void sigpipe_handler(signal_t)
22{
23 puts(string: "SIGPIPE received");
24}
25
26void reader(int fd)
27{
28 char buf[320] = { 0 };
29 const ssize_t bytes_read = read(fd, buffer: buf, size: sizeof(buf));
30 if (bytes_read == -1)
31 perror(string: "reader: read failed"), exit(status: 1);
32
33 printf(format: "reader: read %zu bytes: '%.*s'\n", bytes_read, (int) bytes_read, buf);
34
35 if (bytes_read != (ssize_t) strlen(s: data) + 1)
36 badbadbad();
37
38 printf(format: "read done\n");
39}
40
41void writer(int fd)
42{
43 // syscall_clock_msleep(1000);
44 size_t bytes_written = write(fd, buffer: data, size: strlen(s: data) + 1);
45 if (IS_ERR_VALUE(bytes_written))
46 {
47 if (bytes_written != (size_t) -EPIPE)
48 puts(string: "writer: write failed"), exit(status: 1);
49 }
50 else
51 {
52 printf(format: "writer: wrote %zu bytes\n", bytes_written);
53 }
54}
55
56int main(void)
57{
58 puts(string: "MOS pipe(2) test.");
59 signal(SIGPIPE, handler: sigpipe_handler);
60
61 fd_t fds[2];
62 if (pipe(fds))
63 {
64 perror(string: "pipe(2) failed");
65 return 1;
66 }
67
68 const fd_t r = fds[0], w = fds[1];
69
70 if (fork() == 0)
71 {
72 // child = writer
73 close(fd: r);
74 writer(fd: w);
75 close(fd: w);
76 }
77 else
78 {
79 // parent = reader
80 close(fd: w);
81 reader(fd: r);
82 close(fd: r);
83 }
84
85 return 0;
86}
87