1// SPDX-License-Identifier: GPL-3.0-or-later
2
3#include <fcntl.h>
4#include <mos/syscall/usermode.h>
5#include <stdio.h>
6#include <stdlib.h>
7#include <string.h>
8#include <unistd.h>
9
10#define IPC_METHOD_SYSCALL 0
11#define IPC_METHOD_SYSFS 1
12
13#define IPC_METHOD IPC_METHOD_SYSFS
14
15int main(int argc, char **argv)
16{
17 if (argc != 2)
18 {
19 printf(format: "usage: %s <ping-pong-ipc-channel>\n", argv[0]);
20 printf(format: "connects to the given ipc name and reads a message from it\n");
21 return 1;
22 }
23
24 const char *ipc_name = argv[1];
25 printf(format: "client: connecting to ipc name '%s'\n", ipc_name);
26
27#if IPC_METHOD == IPC_METHOD_SYSCALL
28 const fd_t client = syscall_ipc_connect(ipc_name, MOS_PAGE_SIZE);
29#elif IPC_METHOD == IPC_METHOD_SYSFS
30 const char *basepath = "/sys/ipc/";
31 const size_t path_len = strlen(s: basepath) + strlen(s: ipc_name) + 1;
32 char pathbuf[path_len];
33 strcpy(dest: pathbuf, src: basepath);
34 strcat(dest: pathbuf, src: ipc_name);
35 pathbuf[path_len - 1] = '\0';
36 const fd_t client = open(path: pathbuf, O_RDWR);
37#else
38#error "unknown IPC_METHOD"
39#endif
40
41 if (client < 0)
42 {
43 printf(format: "client: failed to open ipc channel '%s'\n", ipc_name);
44 return 1;
45 }
46
47 size_t bufsize = 0;
48 const size_t readsize = read(fd: client, buffer: &bufsize, size: sizeof(bufsize));
49 if (readsize != sizeof(bufsize))
50 {
51 puts(string: "client: failed to read size from ipc channel");
52 return 1;
53 }
54
55 char *buf = malloc(size: bufsize);
56 const size_t read_size = read(fd: client, buffer: buf, size: bufsize);
57 if (read_size != bufsize)
58 {
59 puts(string: "client: failed to read from ipc channel");
60 return 1;
61 }
62
63 printf(format: "client: received '%.*s'\n", (int) read_size, buf);
64
65 const char *reply = "Hello, Server!";
66 const size_t reply_size = strlen(s: reply) + 1;
67 write(fd: client, buffer: &reply_size, size: sizeof(reply_size));
68 const size_t written = write(fd: client, buffer: reply, size: reply_size);
69
70 if (written != reply_size)
71 {
72 puts(string: "client: failed to write to ipc channel");
73 }
74
75 return 0;
76}
77