Gilad Arnold | 11c066f | 2012-05-10 14:37:25 -0700 | [diff] [blame] | 1 | // Copyright (c) 2012 The Chromium OS Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "update_engine/file_descriptor.h" |
| 6 | |
| 7 | #include <fcntl.h> |
| 8 | #include <sys/stat.h> |
| 9 | #include <sys/types.h> |
| 10 | |
Chris Sosa | fc661a1 | 2013-02-26 14:43:21 -0800 | [diff] [blame] | 11 | #include <base/posix/eintr_wrapper.h> |
Gilad Arnold | 11c066f | 2012-05-10 14:37:25 -0700 | [diff] [blame] | 12 | |
| 13 | namespace chromeos_update_engine { |
| 14 | |
| 15 | bool EintrSafeFileDescriptor::Open(const char* path, int flags, mode_t mode) { |
| 16 | CHECK_EQ(fd_, -1); |
| 17 | return ((fd_ = HANDLE_EINTR(open(path, flags, mode))) >= 0); |
| 18 | } |
| 19 | |
| 20 | bool EintrSafeFileDescriptor::Open(const char* path, int flags) { |
| 21 | CHECK_EQ(fd_, -1); |
| 22 | return ((fd_ = HANDLE_EINTR(open(path, flags))) >= 0); |
| 23 | } |
| 24 | |
| 25 | ssize_t EintrSafeFileDescriptor::Read(void* buf, size_t count) { |
| 26 | CHECK_GE(fd_, 0); |
| 27 | return HANDLE_EINTR(read(fd_, buf, count)); |
| 28 | } |
| 29 | |
| 30 | ssize_t EintrSafeFileDescriptor::Write(const void* buf, size_t count) { |
| 31 | CHECK_GE(fd_, 0); |
| 32 | |
| 33 | // Attempt repeated writes, as long as some progress is being made. |
| 34 | char* char_buf = const_cast<char*>(reinterpret_cast<const char*>(buf)); |
| 35 | ssize_t written = 0; |
| 36 | while (count > 0) { |
| 37 | ssize_t ret = HANDLE_EINTR(write(fd_, char_buf, count)); |
| 38 | |
| 39 | // Fail on either an error or no progress. |
| 40 | if (ret <= 0) |
| 41 | return (written ? written : ret); |
| 42 | written += ret; |
| 43 | count -= ret; |
| 44 | char_buf += ret; |
| 45 | } |
| 46 | return written; |
| 47 | } |
| 48 | |
Nam T. Nguyen | f1d582e | 2014-12-08 15:07:17 -0800 | [diff] [blame] | 49 | off64_t EintrSafeFileDescriptor::Seek(off64_t offset, int whence) { |
| 50 | CHECK_GE(fd_, 0); |
| 51 | return lseek64(fd_, offset, whence); |
| 52 | } |
| 53 | |
Gilad Arnold | 11c066f | 2012-05-10 14:37:25 -0700 | [diff] [blame] | 54 | bool EintrSafeFileDescriptor::Close() { |
| 55 | CHECK_GE(fd_, 0); |
Mike Frysinger | bcee2ca | 2014-05-14 16:28:23 -0400 | [diff] [blame] | 56 | if (IGNORE_EINTR(close(fd_))) |
Gilad Arnold | 6eccc53 | 2012-05-17 15:44:22 -0700 | [diff] [blame] | 57 | return false; |
| 58 | Reset(); |
| 59 | return true; |
| 60 | } |
| 61 | |
| 62 | void EintrSafeFileDescriptor::Reset() { |
| 63 | fd_ = -1; |
| 64 | } |
| 65 | |
Gilad Arnold | 11c066f | 2012-05-10 14:37:25 -0700 | [diff] [blame] | 66 | } // namespace chromeos_update_engine |