1 /*
2  * Copyright (c) 2020 Linaro Limited
3  *
4  * SPDX-License-Identifier: Apache-2.0
5  *
6  * This sample application is roughly based on the sample code in Linux
7  * manpage for eventfd().
8  */
9 #include <sys/eventfd.h>
10 #include <unistd.h>
11 #include <stdlib.h>
12 #include <stdio.h>
13 #include <stdint.h>
14 
15 #define fatal(msg) \
16 	do { perror(msg); exit(EXIT_FAILURE); } while (0)
17 
18 /* As Zephyr doesn't provide command-line args, emulate them. */
19 char *input_argv[] = {"argv0", "1", "2", "3", "4"};
20 
21 int efd;
22 int g_argc;
23 char **g_argv;
24 
writer(void)25 void writer(void)
26 {
27 	int j;
28 	uint64_t u;
29 	ssize_t s;
30 
31 	for (j = 1; j < g_argc; j++) {
32 		printf("Writing %s to efd\n", g_argv[j]);
33 		u = strtoull(g_argv[j], NULL, 0);
34 		s = write(efd, &u, sizeof(uint64_t));
35 		if (s != sizeof(uint64_t)) {
36 			fatal("write");
37 		}
38 	}
39 	printf("Completed write loop\n");
40 }
41 
reader(void)42 void reader(void)
43 {
44 	uint64_t u;
45 	ssize_t s;
46 
47 	sleep(1);
48 
49 	printf("About to read\n");
50 	s = read(efd, &u, sizeof(uint64_t));
51 	if (s != sizeof(uint64_t)) {
52 		fatal("read");
53 	}
54 	printf("Read %llu (0x%llx) from efd\n",
55 	       (unsigned long long)u, (unsigned long long)u);
56 }
57 
main(int argc,char * argv[])58 int main(int argc, char *argv[])
59 {
60 	argv = input_argv;
61 	argc = sizeof(input_argv) / sizeof(input_argv[0]);
62 
63 	if (argc < 2) {
64 		fprintf(stderr, "Usage: %s <num>...\n", argv[0]);
65 		exit(EXIT_FAILURE);
66 	}
67 
68 	g_argc = argc;
69 	g_argv = argv;
70 
71 	efd = eventfd(0, 0);
72 	if (efd == -1) {
73 		fatal("eventfd");
74 	}
75 
76 	writer();
77 	reader();
78 
79 	printf("Finished\n");
80 
81 	return 0;
82 }
83