blob: d1dc9d10eb054f1d7d959aa43b0b3d3ed47fc7af [file] [log] [blame]
Josh Gaoea7457b2016-08-30 15:39:25 -07001/*
2 * Copyright (C) 2016 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#pragma once
18
Josh Gao01aa5e92018-05-24 00:47:05 -070019#include <errno.h>
Josh Gao810fedb2018-05-11 12:55:56 -070020#include <unistd.h>
21
Josh Gaoea7457b2016-08-30 15:39:25 -070022#include <android-base/unique_fd.h>
23
24// Helper to automatically close an FD when it goes out of scope.
25struct AdbCloser {
26 static void Close(int fd);
27};
28
29using unique_fd = android::base::unique_fd_impl<AdbCloser>;
Josh Gao810fedb2018-05-11 12:55:56 -070030
31#if !defined(_WIN32)
Josh Gao2cf03a32018-05-23 11:04:58 -070032inline bool Pipe(unique_fd* read, unique_fd* write, int flags = 0) {
Josh Gao810fedb2018-05-11 12:55:56 -070033 int pipefd[2];
Josh Gao2cf03a32018-05-23 11:04:58 -070034#if !defined(__APPLE__)
35 if (pipe2(pipefd, flags) != 0) {
36 return false;
37 }
38#else
39 // Darwin doesn't have pipe2. Implement it ourselves.
40 if (flags != 0 && (flags & ~(O_CLOEXEC | O_NONBLOCK)) != 0) {
41 errno = EINVAL;
42 return false;
43 }
44
Josh Gao8d7069e2018-05-23 16:44:53 +000045 if (pipe(pipefd) != 0) {
Josh Gao810fedb2018-05-11 12:55:56 -070046 return false;
47 }
Josh Gao2cf03a32018-05-23 11:04:58 -070048
49 if (flags & O_CLOEXEC) {
50 if (fcntl(pipefd[0], F_SETFD, FD_CLOEXEC) != 0 ||
51 fcntl(pipefd[1], F_SETFD, FD_CLOEXEC) != 0) {
Josh Gao01aa5e92018-05-24 00:47:05 -070052 close(pipefd[0]);
53 close(pipefd[1]);
54 return false;
Josh Gao2cf03a32018-05-23 11:04:58 -070055 }
56 }
57
58 if (flags & O_NONBLOCK) {
59 if (fcntl(pipefd[0], F_SETFL, O_NONBLOCK) != 0 ||
60 fcntl(pipefd[1], F_SETFL, O_NONBLOCK) != 0) {
Josh Gao01aa5e92018-05-24 00:47:05 -070061 close(pipefd[0]);
62 close(pipefd[1]);
63 return false;
Josh Gao2cf03a32018-05-23 11:04:58 -070064 }
65 }
66#endif
67
Josh Gao810fedb2018-05-11 12:55:56 -070068 read->reset(pipefd[0]);
69 write->reset(pipefd[1]);
70 return true;
71}
72#endif