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>
21 static void finish_ok(struct io_conn *conn, struct data *d)
28 static struct io_plan *init_conn(struct io_conn *conn, struct data *d)
31 io_set_debug(conn, true);
36 io_set_finish(conn, finish_ok, d);
38 return io_read_partial(conn, d->buf, sizeof(d->buf), &d->bytes,
42 static int make_listen_fd(const char *port, struct addrinfo **info)
45 struct addrinfo *addrinfo, hints;
47 memset(&hints, 0, sizeof(hints));
48 hints.ai_family = AF_UNSPEC;
49 hints.ai_socktype = SOCK_STREAM;
50 hints.ai_flags = AI_PASSIVE;
51 hints.ai_protocol = 0;
53 if (getaddrinfo(NULL, port, &hints, &addrinfo) != 0)
56 fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
57 addrinfo->ai_protocol);
61 setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
62 if (bind(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0) {
66 if (listen(fd, 1) != 0) {
74 static void write_to_socket(const char *str, const struct addrinfo *addrinfo)
78 fd = socket(addrinfo->ai_family, addrinfo->ai_socktype,
79 addrinfo->ai_protocol);
82 if (connect(fd, addrinfo->ai_addr, addrinfo->ai_addrlen) != 0)
84 signal(SIGPIPE, SIG_IGN);
85 for (i = 0; i < strlen(str); i++) {
86 if (write(fd, str + i, 1) != 1)
94 struct data *d = malloc(sizeof(*d));
95 struct addrinfo *addrinfo;
96 struct io_listener *l;
99 /* This is how many tests you plan to run */
102 fd = make_listen_fd(PORT, &addrinfo);
104 l = io_new_listener(NULL, fd, init_conn, d);
108 io_close_listener(l);
109 write_to_socket("hellothere", addrinfo);
110 freeaddrinfo(addrinfo);
114 ok1(io_loop(NULL, NULL) == d);
117 ok1(d->bytes <= sizeof(d->buf));
118 ok1(memcmp(d->buf, "hellothere", d->bytes) == 0);
121 ok1(WIFEXITED(status));
122 ok1(WEXITSTATUS(status) == 0);
126 io_close_listener(l);
127 write_to_socket("hi", addrinfo);
128 freeaddrinfo(addrinfo);
133 ok1(io_loop(NULL, NULL) == d);
136 ok1(d->bytes <= strlen("hi"));
137 ok1(memcmp(d->buf, "hi", d->bytes) == 0);
139 freeaddrinfo(addrinfo);
141 io_close_listener(l);
144 ok1(WIFEXITED(status));
145 ok1(WEXITSTATUS(status) == 0);
147 /* This exits depending on whether all tests passed */
148 return exit_status();