2 * Copyright (c) 2008-2009 Apple Inc. All rights reserved.
4 * @APPLE_APACHE_LICENSE_HEADER_START@
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
10 * http://www.apache.org/licenses/LICENSE-2.0
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
18 * @APPLE_APACHE_LICENSE_HEADER_END@
21 #include "config/config.h"
31 #include <dispatch/dispatch.h>
33 #include "dispatch_test.h"
35 static size_t bytes_total;
36 static size_t bytes_read;
40 const char *path = "/usr/share/dict/words";
43 test_start("Dispatch Source Read");
45 int infd = open(path, O_RDONLY);
50 if (fstat(infd, &sb) == -1) {
54 bytes_total = sb.st_size;
56 if (fcntl(infd, F_SETFL, O_NONBLOCK) != 0) {
61 dispatch_queue_t main_q = dispatch_get_main_queue();
62 test_ptr_notnull("dispatch_get_main_queue", main_q);
64 dispatch_source_t reader;
66 reader = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, infd, 0, main_q);
67 test_ptr_notnull("DISPATCH_SOURCE_TYPE_READ", reader);
69 dispatch_source_set_event_handler(reader, ^{
70 size_t estimated = dispatch_source_get_data(reader);
71 printf("bytes available: %zu\n", estimated);
72 const ssize_t bufsiz = 1024*500; // 500 KB buffer
73 static char buffer[1024*500]; // 500 KB buffer
74 ssize_t actual = read(infd, buffer, sizeof(buffer));
76 printf("bytes read: %zd\n", actual);
77 if (actual < bufsiz) {
78 actual = read(infd, buffer, sizeof(buffer));
80 // confirm EOF condition
81 test_long("EOF", actual, 0);
82 dispatch_source_cancel(reader);
83 dispatch_release(reader);
87 dispatch_source_set_cancel_handler(reader, ^{
88 test_long("Bytes read", bytes_read, bytes_total);
89 int res = close(infd);
90 test_errno("close", res == -1 ? errno : 0, 0);
94 dispatch_resume(reader);