blob: 919c8bb01112646d7c9d4d6cbf97cf9a23e62105 [file] [log] [blame]
Primiano Tucci76499cd2018-11-21 10:54:04 +01001/*
2 * Copyright (C) 2018 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
Primiano Tucci2c5488f2019-06-01 03:27:28 +010017#include "perfetto/ext/base/pipe.h"
Primiano Tucci76499cd2018-11-21 10:54:04 +010018
Primiano Tucci1366dd02020-12-02 10:17:10 +010019#include "perfetto/base/build_config.h"
20
Primiano Tuccid4d08d32020-12-08 15:35:13 +010021#include <fcntl.h> // For O_BINARY (Windows) and F_SETxx (UNIX)
22
Primiano Tucci1366dd02020-12-02 10:17:10 +010023#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
24#include <io.h>
25#else
Primiano Tucci76499cd2018-11-21 10:54:04 +010026#include <sys/types.h>
27#include <unistd.h>
Primiano Tucci1366dd02020-12-02 10:17:10 +010028#endif
Primiano Tucci76499cd2018-11-21 10:54:04 +010029
30#include "perfetto/base/logging.h"
31
32namespace perfetto {
33namespace base {
34
35Pipe::Pipe() = default;
36Pipe::Pipe(Pipe&&) noexcept = default;
37Pipe& Pipe::operator=(Pipe&&) = default;
38
39Pipe Pipe::Create(Flags flags) {
40 int fds[2];
Primiano Tucci1366dd02020-12-02 10:17:10 +010041#if PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
42 PERFETTO_CHECK(_pipe(fds, 256, O_BINARY) == 0);
43#else
Primiano Tucci76499cd2018-11-21 10:54:04 +010044 PERFETTO_CHECK(pipe(fds) == 0);
Primiano Tucci1366dd02020-12-02 10:17:10 +010045 PERFETTO_CHECK(fcntl(fds[0], F_SETFD, FD_CLOEXEC) == 0);
46 PERFETTO_CHECK(fcntl(fds[1], F_SETFD, FD_CLOEXEC) == 0);
47#endif
Primiano Tucci76499cd2018-11-21 10:54:04 +010048 Pipe p;
49 p.rd.reset(fds[0]);
50 p.wr.reset(fds[1]);
51
Primiano Tucci1366dd02020-12-02 10:17:10 +010052#if !PERFETTO_BUILDFLAG(PERFETTO_OS_WIN)
Primiano Tucci76499cd2018-11-21 10:54:04 +010053 if (flags == kBothNonBlock || flags == kRdNonBlock) {
54 int cur_flags = fcntl(*p.rd, F_GETFL, 0);
55 PERFETTO_CHECK(cur_flags >= 0);
56 PERFETTO_CHECK(fcntl(*p.rd, F_SETFL, cur_flags | O_NONBLOCK) == 0);
57 }
58
59 if (flags == kBothNonBlock || flags == kWrNonBlock) {
60 int cur_flags = fcntl(*p.wr, F_GETFL, 0);
61 PERFETTO_CHECK(cur_flags >= 0);
62 PERFETTO_CHECK(fcntl(*p.wr, F_SETFL, cur_flags | O_NONBLOCK) == 0);
63 }
Primiano Tucci1366dd02020-12-02 10:17:10 +010064#else
65 PERFETTO_CHECK(flags == kBothBlock);
66#endif
Primiano Tucci76499cd2018-11-21 10:54:04 +010067 return p;
68}
69
70} // namespace base
71} // namespace perfetto