James Kuszmaul | 3224b8e | 2022-01-07 19:00:39 -0800 | [diff] [blame^] | 1 | #include "aos/util/scoped_pipe.h" |
| 2 | |
| 3 | #include <fcntl.h> |
| 4 | #include "glog/logging.h" |
| 5 | |
| 6 | namespace aos::util { |
| 7 | |
| 8 | ScopedPipe::ScopedPipe(int fd) : fd_(fd) {} |
| 9 | |
| 10 | ScopedPipe::~ScopedPipe() { |
| 11 | if (fd_ != -1) { |
| 12 | PCHECK(close(fd_) != -1); |
| 13 | } |
| 14 | } |
| 15 | |
| 16 | ScopedPipe::ScopedPipe(ScopedPipe &&scoped_pipe) : fd_(scoped_pipe.fd_) { |
| 17 | scoped_pipe.fd_ = -1; |
| 18 | } |
| 19 | |
| 20 | ScopedPipe &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 | |
| 29 | std::tuple<ScopedPipe::ScopedReadPipe, ScopedPipe::ScopedWritePipe> |
| 30 | ScopedPipe::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 | |
| 38 | std::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 | |
| 48 | void 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 |