1 /*
2 *
3 * Copyright 2015 gRPC authors.
4 *
5 * Licensed under the Apache License, Version 2.0 (the "License");
6 * you may not use this file except in compliance with the License.
7 * You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 *
17 */
18
19 #include <grpc/support/port_platform.h>
20
21 #include "src/core/lib/iomgr/port.h"
22
23 #ifdef GRPC_POSIX_WAKEUP_FD
24
25 #include "src/core/lib/iomgr/wakeup_fd_pipe.h"
26 #include "src/core/lib/iomgr/wakeup_fd_posix.h"
27
28 #include <errno.h>
29 #include <string.h>
30 #include <unistd.h>
31
32 #include <grpc/support/log.h>
33
34 #include "src/core/lib/iomgr/socket_utils_posix.h"
35
pipe_init(grpc_wakeup_fd * fd_info)36 static grpc_error* pipe_init(grpc_wakeup_fd* fd_info) {
37 int pipefd[2];
38 int r = pipe(pipefd);
39 if (0 != r) {
40 gpr_log(GPR_ERROR, "pipe creation failed (%d): %s", errno, strerror(errno));
41 return GRPC_OS_ERROR(errno, "pipe");
42 }
43 grpc_error* err;
44 err = grpc_set_socket_nonblocking(pipefd[0], 1);
45 if (err != GRPC_ERROR_NONE) return err;
46 err = grpc_set_socket_nonblocking(pipefd[1], 1);
47 if (err != GRPC_ERROR_NONE) return err;
48 fd_info->read_fd = pipefd[0];
49 fd_info->write_fd = pipefd[1];
50 return GRPC_ERROR_NONE;
51 }
52
pipe_consume(grpc_wakeup_fd * fd_info)53 static grpc_error* pipe_consume(grpc_wakeup_fd* fd_info) {
54 char buf[128];
55 ssize_t r;
56
57 for (;;) {
58 r = read(fd_info->read_fd, buf, sizeof(buf));
59 if (r > 0) continue;
60 if (r == 0) return GRPC_ERROR_NONE;
61 switch (errno) {
62 case EAGAIN:
63 return GRPC_ERROR_NONE;
64 case EINTR:
65 continue;
66 default:
67 return GRPC_OS_ERROR(errno, "read");
68 }
69 }
70 }
71
pipe_wakeup(grpc_wakeup_fd * fd_info)72 static grpc_error* pipe_wakeup(grpc_wakeup_fd* fd_info) {
73 char c = 0;
74 while (write(fd_info->write_fd, &c, 1) != 1 && errno == EINTR)
75 ;
76 return GRPC_ERROR_NONE;
77 }
78
pipe_destroy(grpc_wakeup_fd * fd_info)79 static void pipe_destroy(grpc_wakeup_fd* fd_info) {
80 if (fd_info->read_fd != 0) close(fd_info->read_fd);
81 if (fd_info->write_fd != 0) close(fd_info->write_fd);
82 }
83
pipe_check_availability(void)84 static int pipe_check_availability(void) {
85 grpc_wakeup_fd fd;
86 fd.read_fd = fd.write_fd = -1;
87
88 if (pipe_init(&fd) == GRPC_ERROR_NONE) {
89 pipe_destroy(&fd);
90 return 1;
91 } else {
92 return 0;
93 }
94 }
95
96 const grpc_wakeup_fd_vtable grpc_pipe_wakeup_fd_vtable = {
97 pipe_init, pipe_consume, pipe_wakeup, pipe_destroy,
98 pipe_check_availability};
99
100 #endif /* GPR_POSIX_WAKUP_FD */
101