|
| 1 | +/* |
| 2 | + * Copyright (c) 2019 Apple Inc. All rights reserved. |
| 3 | + * |
| 4 | + * @APPLE_APACHE_LICENSE_HEADER_START@ |
| 5 | + * |
| 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 |
| 9 | + * |
| 10 | + * http://www.apache.org/licenses/LICENSE-2.0 |
| 11 | + * |
| 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. |
| 17 | + * |
| 18 | + * @APPLE_APACHE_LICENSE_HEADER_END@ |
| 19 | + */ |
| 20 | + |
| 21 | +#include <stdio.h> |
| 22 | +#include <unistd.h> |
| 23 | +#include <stdlib.h> |
| 24 | +#include <limits.h> |
| 25 | +#include <errno.h> |
| 26 | + |
| 27 | +#include <bsdtests.h> |
| 28 | +#include "dispatch_test.h" |
| 29 | +#include <dispatch/dispatch.h> |
| 30 | + |
| 31 | +int |
| 32 | +main() { |
| 33 | + int pipe_fds[2] = { -1, -1 }; |
| 34 | + int pipe_err = pipe(pipe_fds); |
| 35 | + int readFD = pipe_fds[0]; |
| 36 | + int writeFD = pipe_fds[1]; |
| 37 | + |
| 38 | + dispatch_test_start(NULL); |
| 39 | + if (pipe_err) { |
| 40 | + test_errno("pipe", errno, 0); |
| 41 | + test_stop(); |
| 42 | + _Exit(EXIT_FAILURE); |
| 43 | + } |
| 44 | + |
| 45 | + printf("readFD=%d, writeFD=%d\n", readFD, writeFD); |
| 46 | + dispatch_queue_t q = dispatch_queue_create("q", NULL); |
| 47 | + dispatch_io_t io = dispatch_io_create(DISPATCH_IO_STREAM, readFD, q, ^(int err) { |
| 48 | + printf("cleanup, err=%d\n", err); |
| 49 | + close(readFD); |
| 50 | + printf("all done\n"); |
| 51 | + test_stop(); |
| 52 | + _Exit(EXIT_SUCCESS); |
| 53 | + }); |
| 54 | + dispatch_io_set_low_water(io, 0); |
| 55 | + dispatch_io_read(io, 0, UINT_MAX, q, ^(bool done, dispatch_data_t data, int err) { |
| 56 | + printf("read: \%d, %zu, %d\n", done, data == NULL ? 0 : dispatch_data_get_size(data), err); |
| 57 | + if (data != NULL && dispatch_data_get_size(data) > 0) { |
| 58 | + // will only happen once |
| 59 | + printf("closing writeFD\n"); |
| 60 | + close(writeFD); |
| 61 | + dispatch_after(DISPATCH_TIME_NOW + 1, q, ^{ |
| 62 | + dispatch_io_close(io, 0); |
| 63 | + }); |
| 64 | + } |
| 65 | + }); |
| 66 | + dispatch_resume(io); |
| 67 | + printf("writing\n"); |
| 68 | + write(writeFD, "x", 1); |
| 69 | + printf("wrtten\n"); |
| 70 | + dispatch_main(); |
| 71 | +} |
0 commit comments