blob: 76bd974bbe4818a282d86ad37b350b79bf7372db [file] [log] [blame]
Colin Crossbcb4ed32016-01-14 15:35:40 -08001/*
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#ifndef LIBMEMUNREACHABLE_SCOPED_PIPE_H_
18#define LIBMEMUNREACHABLE_SCOPED_PIPE_H_
19
20#include <unistd.h>
21
22#include "log.h"
23
24class ScopedPipe {
25 public:
26 ScopedPipe() : pipefd_{-1, -1} {
27 int ret = pipe2(pipefd_, O_CLOEXEC);
28 if (ret < 0) {
Christopher Ferris47dea712017-05-03 17:34:29 -070029 MEM_LOG_ALWAYS_FATAL("failed to open pipe");
Colin Crossbcb4ed32016-01-14 15:35:40 -080030 }
31 }
Colin Crossa83881e2017-06-22 10:50:05 -070032 ~ScopedPipe() { Close(); }
Colin Crossbcb4ed32016-01-14 15:35:40 -080033
34 ScopedPipe(ScopedPipe&& other) {
35 SetReceiver(other.ReleaseReceiver());
36 SetSender(other.ReleaseSender());
37 }
38
Colin Crossa83881e2017-06-22 10:50:05 -070039 ScopedPipe& operator=(ScopedPipe&& other) {
Colin Crossbcb4ed32016-01-14 15:35:40 -080040 SetReceiver(other.ReleaseReceiver());
41 SetSender(other.ReleaseSender());
42 return *this;
43 }
44
Colin Crossa83881e2017-06-22 10:50:05 -070045 void CloseReceiver() { close(ReleaseReceiver()); }
Colin Crossbcb4ed32016-01-14 15:35:40 -080046
Colin Crossa83881e2017-06-22 10:50:05 -070047 void CloseSender() { close(ReleaseSender()); }
Colin Crossbcb4ed32016-01-14 15:35:40 -080048
49 void Close() {
50 CloseReceiver();
51 CloseSender();
52 }
53
54 int Receiver() { return pipefd_[0]; }
55 int Sender() { return pipefd_[1]; }
56
57 int ReleaseReceiver() {
58 int ret = Receiver();
59 SetReceiver(-1);
60 return ret;
61 }
62
63 int ReleaseSender() {
64 int ret = Sender();
65 SetSender(-1);
66 return ret;
67 }
68
69 private:
70 void SetReceiver(int fd) { pipefd_[0] = fd; };
71 void SetSender(int fd) { pipefd_[1] = fd; };
72
73 int pipefd_[2];
74};
75#endif