]> git.saurik.com Git - apple/libdispatch.git/blob - testing/dispatch_read2.c
libdispatch-84.5.3.tar.gz
[apple/libdispatch.git] / testing / dispatch_read2.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_t reader = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, infd, 0, main_q);
43 test_ptr_notnull("dispatch_source_create", reader);
44 assert(reader);
45
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));
52 bytes_read += actual;
53 printf("bytes read: %zd\n", actual);
54 if (actual < bufsiz) {
55 actual = read(infd, buffer, sizeof(buffer));
56 bytes_read += actual;
57 // confirm EOF condition
58 test_long("EOF", actual, 0);
59 dispatch_source_cancel(reader);
60 }
61 });
62 dispatch_source_set_cancel_handler(reader, ^{
63 test_long("Bytes read", bytes_read, bytes_total);
64 test_stop();
65 });
66 dispatch_resume(reader);
67
68 dispatch_main();
69 }