dispatch_io_pipe_close.c 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. #include <stdio.h>
  21. #include <stdlib.h>
  22. #include <limits.h>
  23. #include <errno.h>
  24. #if defined(__unix__) || (defined(__APPLE__) && defined(__MACH__))
  25. #include <unistd.h>
  26. #elif defined(_WIN32)
  27. #include <Windows.h>
  28. #endif
  29. #include <bsdtests.h>
  30. #include "dispatch_test.h"
  31. #include <dispatch/dispatch.h>
  32. int
  33. main() {
  34. dispatch_test_start(NULL);
  35. #if defined(_WIN32)
  36. dispatch_fd_t readFD, writeFD;
  37. if (!CreatePipe((PHANDLE)&readFD, (PHANDLE)&writeFD, NULL, 0)) {
  38. test_long("CreatePipe", GetLastError(), ERROR_SUCCESS);
  39. test_stop();
  40. _Exit(EXIT_FAILURE);
  41. }
  42. #else
  43. int pipe_fds[2] = { -1, -1 };
  44. int pipe_err = pipe(pipe_fds);
  45. int readFD = pipe_fds[0];
  46. int writeFD = pipe_fds[1];
  47. if (pipe_err) {
  48. test_errno("pipe", errno, 0);
  49. test_stop();
  50. _Exit(EXIT_FAILURE);
  51. }
  52. #endif
  53. printf("readFD=%lld, writeFD=%lld\n", (long long)readFD, (long long)writeFD);
  54. dispatch_queue_t q = dispatch_queue_create("q", NULL);
  55. dispatch_io_t io = dispatch_io_create(DISPATCH_IO_STREAM, readFD, q, ^(int err) {
  56. printf("cleanup, err=%d\n", err);
  57. dispatch_test_fd_close(readFD);
  58. printf("all done\n");
  59. test_stop();
  60. _Exit(EXIT_SUCCESS);
  61. });
  62. dispatch_io_set_low_water(io, 0);
  63. dispatch_io_read(io, 0, UINT_MAX, q, ^(bool done, dispatch_data_t data, int err) {
  64. printf("read: \%d, %zu, %d\n", done, data == NULL ? 0 : dispatch_data_get_size(data), err);
  65. if (data != NULL && dispatch_data_get_size(data) > 0) {
  66. // will only happen once
  67. printf("closing writeFD\n");
  68. dispatch_test_fd_close(writeFD);
  69. dispatch_after(DISPATCH_TIME_NOW + 1, q, ^{
  70. dispatch_io_close(io, 0);
  71. });
  72. }
  73. });
  74. dispatch_resume(io);
  75. printf("writing\n");
  76. dispatch_test_fd_write(writeFD, "x", 1);
  77. printf("wrtten\n");
  78. dispatch_main();
  79. }