9 #include <dispatch/dispatch.h>
11 #include "dispatch_test.h"
13 static size_t bytes_total
;
14 static size_t bytes_read
;
18 const char *path
= "/usr/share/dict/words";
21 test_start("Dispatch Source Read");
23 int infd
= open(path
, O_RDONLY
);
28 if (fstat(infd
, &sb
) == -1) {
32 bytes_total
= sb
.st_size
;
34 if (fcntl(infd
, F_SETFL
, O_NONBLOCK
) != 0) {
39 dispatch_queue_t main_q
= dispatch_get_main_queue();
40 test_ptr_notnull("dispatch_get_main_queue", main_q
);
42 dispatch_source_attr_t attr
= dispatch_source_attr_create();
43 test_ptr_notnull("dispatch_source_attr_create", attr
);
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);
52 dispatch_source_t reader
= dispatch_source_read_create(infd
, attr
,
53 main_q
, ^(dispatch_event_t ev
) {
55 long err_dom
= dispatch_event_get_error(ev
, &err_val
);
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
));
63 printf("bytes read: %zd\n", actual
);
64 if (actual
< bufsiz
) {
65 actual
= read(infd
, buffer
, sizeof(buffer
));
67 // confirm EOF condition
68 test_long("EOF", actual
, 0);
69 dispatch_release(dispatch_event_get_source(ev
));
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
);
78 printf("reader = %p\n", reader
);
81 dispatch_release(attr
);