2 * Copyright (c) 2008-2011 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@
22 #include <sys/types.h>
30 #include <dispatch/dispatch.h>
33 #include "dispatch_test.h"
35 static size_t bytes_total;
36 static size_t bytes_read;
41 test_ptr("test_fin run", cxt, cxt);
48 const char *path = "/usr/share/dict/words";
51 dispatch_test_start("Dispatch Source Read");
53 int infd = open(path, O_RDONLY);
58 if (fstat(infd, &sb) == -1) {
62 bytes_total = sb.st_size;
64 if (fcntl(infd, F_SETFL, O_NONBLOCK) != 0) {
69 if (!dispatch_test_check_evfilt_read_for_fd(infd)) {
70 test_skip("EVFILT_READ kevent not firing for test file");
74 dispatch_queue_t main_q = dispatch_get_main_queue();
75 test_ptr_notnull("dispatch_get_main_queue", main_q);
77 dispatch_source_t reader = dispatch_source_create(DISPATCH_SOURCE_TYPE_READ, infd, 0, main_q);
78 test_ptr_notnull("dispatch_source_create", reader);
81 dispatch_source_set_event_handler(reader, ^{
82 size_t estimated = dispatch_source_get_data(reader);
83 fprintf(stderr, "bytes available: %zu\n", estimated);
84 test_double_less_than_or_equal("estimated", estimated, bytes_total - bytes_read);
85 const ssize_t bufsiz = 1024*500; // 500 KB buffer
86 static char buffer[1024*500]; // 500 KB buffer
87 ssize_t actual = read(infd, buffer, sizeof(buffer));
89 printf("bytes read: %zd\n", actual);
90 if (actual < bufsiz) {
91 actual = read(infd, buffer, sizeof(buffer));
93 // confirm EOF condition
94 test_long("EOF", actual, 0);
95 dispatch_source_cancel(reader);
99 dispatch_source_set_cancel_handler(reader, ^{
100 test_long("Bytes read", bytes_read, bytes_total);
101 int res = close(infd);
102 test_errno("close", res == -1 ? errno : 0, 0);
103 dispatch_release(reader);
106 dispatch_set_context(reader, reader);
107 dispatch_set_finalizer_f(reader, test_fin);
109 dispatch_resume(reader);