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_t reader
= dispatch_source_create(DISPATCH_SOURCE_TYPE_READ
, infd
, 0, main_q
);
43 test_ptr_notnull("dispatch_source_create", reader
);
46 dispatch_source_set_event_handler(reader
, ^{
47 size_t estimated
= dispatch_source_get_data(reader
);
48 printf("bytes available: %zu\n", estimated
);
49 const ssize_t bufsiz
= 1024*500; // 500 KB buffer
50 static char buffer
[1024*500]; // 500 KB buffer
51 ssize_t actual
= read(infd
, buffer
, sizeof(buffer
));
53 printf("bytes read: %zd\n", actual
);
54 if (actual
< bufsiz
) {
55 actual
= read(infd
, buffer
, sizeof(buffer
));
57 // confirm EOF condition
58 test_long("EOF", actual
, 0);
59 dispatch_source_cancel(reader
);
62 dispatch_source_set_cancel_handler(reader
, ^{
63 test_long("Bytes read", bytes_read
, bytes_total
);
66 dispatch_resume(reader
);