blob: 3a17e0305018d6772df2dfcae4f615349b25dbfb [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]);
Yifan Hongb9d19c82018-08-02 14:09:55 -070080 CloseFd(&mFds[0]);
Andreas Huber28d35912017-03-24 13:14:11 -070081
Yi Kong19d5c002018-07-20 13:39:55 -070082 if (mThread != nullptr) {
Andreas Huber28d35912017-03-24 13:14:11 -070083 mThread->join();
84 mThread.clear();
85 }
Andreas Huber28d35912017-03-24 13:14:11 -070086}
87
88status_t PipeRelay::initCheck() const {
89 return mInitCheck;
90}
91
92int PipeRelay::fd() const {
93 return mFds[1];
94}
95
96} // namespace lshal
97} // namespace android