]> git.ozlabs.org Git - ccan/blob - ccan/io/test/run-01-start-finish.c
ccan/io: get rid of io_next(), pass callbacks directly.
[ccan] / ccan / io / test / run-01-start-finish.c
1 #include <ccan/io/io.h>
2 /* Include the C files directly. */
3 #include <ccan/io/poll.c>
4 #include <ccan/io/io.c>
5 #include <ccan/tap/tap.h>
6 #include <sys/wait.h>
7 #include <stdio.h>
8
9 static struct io_plan *start_ok(struct io_conn *conn, int *state)
10 {
11         ok1(*state == 0);
12         (*state)++;
13         return io_close(conn, NULL);
14 }
15
16 static void finish_ok(struct io_conn *conn, int *state)
17 {
18         ok1(*state == 1);
19         (*state)++;
20         io_break(conn, state + 1, NULL, NULL);
21 }
22
23 static int make_listen_fd(const char *port, struct addrinfo **info)
24 {
25         int fd, on = 1;
26         struct addrinfo *addrinfo, hints;
27
28         memset(&hints, 0, sizeof(hints));
29         hints.ai_family = AF_UNSPEC;
30         hints.ai_socktype = SOCK_STREAM;
31         hints.ai_flags = AI_PASSIVE;
32         hints.ai_protocol = 0;
33
34         if (getaddrinfo(NULL, port, &hints, &addrinfo) != 0)
35                 return -1;
36
37         fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
38                     addrinfo->ai_protocol);
39         if (fd < 0)
40                 return -1;
41
42         setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
43         if (bind(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
44                 close(fd);
45                 return -1;
46         }
47         if (listen(fd, 1) != 0) {
48                 close(fd);
49                 return -1;
50         }
51         *info = addrinfo;
52         return fd;
53 }
54
55 int main(void)
56 {
57         int state = 0;
58         struct addrinfo *addrinfo;
59         struct io_listener *l;
60         int fd;
61
62         /* This is how many tests you plan to run */
63         plan_tests(9);
64         fd = make_listen_fd("65001", &addrinfo);
65         ok1(fd >= 0);
66         l = io_new_listener(fd, start_ok, finish_ok, &state);
67         ok1(l);
68         fflush(stdout);
69         if (!fork()) {
70                 io_close_listener(l);
71                 fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
72                             addrinfo->ai_protocol);
73                 if (fd < 0)
74                         exit(1);
75                 if (connect(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0)
76                         exit(2);
77                 close(fd);
78                 freeaddrinfo(addrinfo);
79                 exit(0);
80         }
81         freeaddrinfo(addrinfo);
82         ok1(io_loop() == &state + 1);
83         ok1(state == 2);
84         io_close_listener(l);
85         ok1(wait(&state));
86         ok1(WIFEXITED(state));
87         ok1(WEXITSTATUS(state) == 0);
88
89         /* This exits depending on whether all tests passed */
90         return exit_status();
91 }