]> git.saurik.com Git - apple/libdispatch.git/blob - testing/dispatch_read.c
libdispatch-84.5.3.tar.gz
[apple/libdispatch.git] / testing / dispatch_read.c
1 #include <sys/stat.h>
2 #include <assert.h>
3 #include <fcntl.h>
4 #include <stdio.h>
5 #include <stdlib.h>
6 #include <unistd.h>
7 #include <errno.h>
8
9 #include <dispatch/dispatch.h>
10
11 #include "dispatch_test.h"
12
13 static size_t bytes_total;
14 static size_t bytes_read;
15
16 int main(void)
17 {
18 const char *path = "/usr/share/dict/words";
19 struct stat sb;
20
21 test_start("Dispatch Source Read");
22
23 int infd = open(path, O_RDONLY);
24 if (infd == -1) {
25 perror(path);
26 exit(EXIT_FAILURE);
27 }
28 if (fstat(infd, &sb) == -1) {
29 perror(path);
30 exit(EXIT_FAILURE);
31 }
32 bytes_total = sb.st_size;
33
34 if (fcntl(infd, F_SETFL, O_NONBLOCK) != 0) {
35 perror(path);
36 exit(EXIT_FAILURE);
37 }
38
39 dispatch_queue_t main_q = dispatch_get_main_queue();
40 test_ptr_notnull("dispatch_get_main_queue", main_q);
41
42 dispatch_source_attr_t attr = dispatch_source_attr_create();
43 test_ptr_notnull("dispatch_source_attr_create", attr);
44
45 dispatch_source_attr_set_finalizer(attr, ^(dispatch_source_t ds) {
46 test_ptr_notnull("finalizer ran", ds);
47 int res = close(infd);
48 test_errno("close", res == -1 ? errno : 0, 0);
49 test_stop();
50 });
51
52 dispatch_source_t reader = dispatch_source_read_create(infd, attr,
53 main_q, ^(dispatch_event_t ev) {
54 long err_val;
55 long err_dom = dispatch_event_get_error(ev, &err_val);
56 if (!err_dom) {
57 size_t estimated = dispatch_event_get_bytes_available(ev);
58 printf("bytes available: %zu\n", estimated);
59 const ssize_t bufsiz = 1024*500; // 500 KB buffer
60 static char buffer[1024*500]; // 500 KB buffer
61 ssize_t actual = read(infd, buffer, sizeof(buffer));
62 bytes_read += actual;
63 printf("bytes read: %zd\n", actual);
64 if (actual < bufsiz) {
65 actual = read(infd, buffer, sizeof(buffer));
66 bytes_read += actual;
67 // confirm EOF condition
68 test_long("EOF", actual, 0);
69 dispatch_release(dispatch_event_get_source(ev));
70 }
71 } else {
72 test_long("Error domain", err_dom, DISPATCH_ERROR_DOMAIN_POSIX);
73 test_long("Error value", err_val, ECANCELED);
74 test_long("Bytes read", bytes_read, bytes_total);
75 }
76 });
77
78 printf("reader = %p\n", reader);
79 assert(reader);
80
81 dispatch_release(attr);
82
83 dispatch_main();
84 }