blob: 8cf2957f871a83d54774963b9284e85665793967 [file] [log] [blame]
James Kuszmaul3224b8e2022-01-07 19:00:39 -08001#include "aos/util/scoped_pipe.h"
2
3#include <fcntl.h>
4#include "glog/logging.h"
5
6namespace aos::util {
7
8ScopedPipe::ScopedPipe(int fd) : fd_(fd) {}
9
10ScopedPipe::~ScopedPipe() {
11 if (fd_ != -1) {
12 PCHECK(close(fd_) != -1);
13 }
14}
15
16ScopedPipe::ScopedPipe(ScopedPipe &&scoped_pipe) : fd_(scoped_pipe.fd_) {
17 scoped_pipe.fd_ = -1;
18}
19
20ScopedPipe &ScopedPipe::operator=(ScopedPipe &&scoped_pipe) {
21 if (fd_ != -1) {
22 PCHECK(close(fd_) != -1);
23 }
24 fd_ = scoped_pipe.fd_;
25 scoped_pipe.fd_ = -1;
26 return *this;
27}
28
29std::tuple<ScopedPipe::ScopedReadPipe, ScopedPipe::ScopedWritePipe>
30ScopedPipe::MakePipe() {
31 int fds[2];
32 PCHECK(pipe(fds) != -1);
33 PCHECK(fcntl(fds[0], F_SETFL, fcntl(fds[0], F_GETFL) | O_NONBLOCK) != -1);
34 PCHECK(fcntl(fds[1], F_SETFL, fcntl(fds[1], F_GETFL) | O_NONBLOCK) != -1);
35 return {ScopedReadPipe(fds[0]), ScopedWritePipe(fds[1])};
36}
37
38std::optional<uint32_t> ScopedPipe::ScopedReadPipe::Read() {
39 uint32_t buf;
40 ssize_t result = read(fd(), &buf, sizeof(buf));
41 if (result == sizeof(buf)) {
42 return buf;
43 } else {
44 return std::nullopt;
45 }
46}
47
48void ScopedPipe::ScopedWritePipe::Write(uint32_t data) {
49 ssize_t result = write(fd(), &data, sizeof(data));
50 PCHECK(result != -1);
51 CHECK(result == sizeof(data));
52}
53
54} // namespace aos::util