]> git.ozlabs.org Git - ccan/blob - ccan/io/test/run-30-io_flush_sync.c
io: add io_flush_sync().
[ccan] / ccan / io / test / run-30-io_flush_sync.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 size_t bytes_written;
10
11 /* Should be called multiple times, since only writes 1 byte. */
12 static int do_controlled_write(int fd, struct io_plan_arg *arg)
13 {
14         ssize_t ret;
15
16         ret = write(fd, arg->u1.cp, 1);
17         if (ret < 0)
18                 return -1;
19         bytes_written += ret;
20         arg->u1.cp += ret;
21         arg->u2.s -= ret;
22         return arg->u2.s == 0;
23 }
24
25 static int do_error(int fd, struct io_plan_arg *arg)
26 {
27         errno = 1001;
28         return -1;
29 }
30
31 static struct io_plan *conn_wait(struct io_conn *conn, void *unused)
32 {
33         return io_wait(conn, conn, io_never, NULL);
34 }
35
36 static struct io_plan *init_conn_writer(struct io_conn *conn, const char *str)
37 {
38         struct io_plan_arg *arg = io_plan_arg(conn, IO_OUT);
39
40         arg->u1.const_vp = str;
41         arg->u2.s = strlen(str);
42
43         return io_set_plan(conn, IO_OUT, do_controlled_write, conn_wait, NULL);
44 }
45
46 static struct io_plan *init_conn_reader(struct io_conn *conn, void *dst)
47 {
48         /* Never actually succeeds. */
49         return io_read(conn, dst, 1000, io_never, NULL);
50 }
51
52 static struct io_plan *init_conn_error(struct io_conn *conn, void *unused)
53 {
54         io_plan_arg(conn, IO_OUT);
55         return io_set_plan(conn, IO_OUT, do_error, io_never, NULL);
56 }
57
58 int main(void)
59 {
60         int fd = open("/dev/null", O_RDWR);
61         const tal_t *ctx = tal(NULL, char);
62         struct io_conn *conn;
63
64         /* This is how many tests you plan to run */
65         plan_tests(9);
66
67         conn = io_new_conn(ctx, fd, init_conn_writer, "hello");
68         ok1(bytes_written == 0);
69
70         ok1(io_flush_sync(conn));
71         ok1(bytes_written == strlen("hello"));
72
73         /* This won't do anything */
74         ok1(io_flush_sync(conn));
75         ok1(bytes_written == strlen("hello"));
76
77         /* It's reading, this won't do anything. */
78         conn = io_new_conn(ctx, fd, init_conn_reader, ctx);
79         ok1(io_flush_sync(conn));
80         ok1(bytes_written == strlen("hello"));
81
82         /* Now test error state. */
83         conn = io_new_conn(ctx, fd, init_conn_error, ctx);
84         ok1(!io_flush_sync(conn));
85         ok1(errno == 1001);
86
87         tal_free(ctx);
88
89         /* This exits depending on whether all tests passed */
90         return exit_status();
91 }