blob: 87d75ac2d46acf1fa46ea97ee1c3bc2aee421be9 [file] [log] [blame]
Andreas Huber28d35912017-03-24 13:14:11 -07001/*
2 * Copyright (C) 2017 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#include "PipeRelay.h"
18
Andreas Huber28d35912017-03-24 13:14:11 -070019#include <utils/Thread.h>
20
21namespace android {
22namespace lshal {
23
24struct PipeRelay::RelayThread : public Thread {
25 explicit RelayThread(int fd, std::ostream &os);
26
27 bool threadLoop() override;
28
29private:
30 int mFd;
31 std::ostream &mOutStream;
32
33 DISALLOW_COPY_AND_ASSIGN(RelayThread);
34};
35
36////////////////////////////////////////////////////////////////////////////////
37
38PipeRelay::RelayThread::RelayThread(int fd, std::ostream &os)
39 : mFd(fd),
40 mOutStream(os) {
41}
42
43bool PipeRelay::RelayThread::threadLoop() {
44 char buffer[1024];
45 ssize_t n = read(mFd, buffer, sizeof(buffer));
46
47 if (n <= 0) {
48 return false;
49 }
50
51 mOutStream.write(buffer, n);
52
53 return true;
54}
55
56////////////////////////////////////////////////////////////////////////////////
57
58PipeRelay::PipeRelay(std::ostream &os)
Chih-Hung Hsieh734e3782017-10-05 13:44:13 -070059 : mInitCheck(NO_INIT) {
Andreas Huber7dfac442018-05-22 12:56:38 -070060 int res = pipe(mFds);
Andreas Huber28d35912017-03-24 13:14:11 -070061
62 if (res < 0) {
63 mInitCheck = -errno;
64 return;
65 }
66
67 mThread = new RelayThread(mFds[0], os);
68 mInitCheck = mThread->run("RelayThread");
69}
70
Andreas Huber28d35912017-03-24 13:14:11 -070071void PipeRelay::CloseFd(int *fd) {
72 if (*fd >= 0) {
73 close(*fd);
74 *fd = -1;
75 }
76}
77
78PipeRelay::~PipeRelay() {
Andreas Huber7dfac442018-05-22 12:56:38 -070079 CloseFd(&mFds[1]);
Andreas Huber28d35912017-03-24 13:14:11 -070080
Yi Kong19d5c002018-07-20 13:39:55 -070081 if (mThread != nullptr) {
Andreas Huber28d35912017-03-24 13:14:11 -070082 mThread->join();
83 mThread.clear();
84 }
Yifan Honga5ae7862018-09-26 16:07:12 -070085
86 CloseFd(&mFds[0]);
Andreas Huber28d35912017-03-24 13:14:11 -070087}
88
89status_t PipeRelay::initCheck() const {
90 return mInitCheck;
91}
92
93int PipeRelay::fd() const {
94 return mFds[1];
95}
96
97} // namespace lshal
98} // namespace android