blob: 8b8fa728905800a43be19c63a32a8956af12509a [file] [log] [blame]
Alex Deymoaea4c1c2015-08-19 20:24:43 -07001//
2// Copyright (C) 2012 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//
Gilad Arnold11c066f2012-05-10 14:37:25 -070016
17#include "update_engine/file_descriptor.h"
18
19#include <fcntl.h>
20#include <sys/stat.h>
21#include <sys/types.h>
22
Chris Sosafc661a12013-02-26 14:43:21 -080023#include <base/posix/eintr_wrapper.h>
Gilad Arnold11c066f2012-05-10 14:37:25 -070024
25namespace chromeos_update_engine {
26
27bool EintrSafeFileDescriptor::Open(const char* path, int flags, mode_t mode) {
28 CHECK_EQ(fd_, -1);
29 return ((fd_ = HANDLE_EINTR(open(path, flags, mode))) >= 0);
30}
31
32bool EintrSafeFileDescriptor::Open(const char* path, int flags) {
33 CHECK_EQ(fd_, -1);
34 return ((fd_ = HANDLE_EINTR(open(path, flags))) >= 0);
35}
36
37ssize_t EintrSafeFileDescriptor::Read(void* buf, size_t count) {
38 CHECK_GE(fd_, 0);
39 return HANDLE_EINTR(read(fd_, buf, count));
40}
41
42ssize_t EintrSafeFileDescriptor::Write(const void* buf, size_t count) {
43 CHECK_GE(fd_, 0);
44
45 // Attempt repeated writes, as long as some progress is being made.
46 char* char_buf = const_cast<char*>(reinterpret_cast<const char*>(buf));
47 ssize_t written = 0;
48 while (count > 0) {
49 ssize_t ret = HANDLE_EINTR(write(fd_, char_buf, count));
50
51 // Fail on either an error or no progress.
52 if (ret <= 0)
53 return (written ? written : ret);
54 written += ret;
55 count -= ret;
56 char_buf += ret;
57 }
58 return written;
59}
60
Nam T. Nguyenf1d582e2014-12-08 15:07:17 -080061off64_t EintrSafeFileDescriptor::Seek(off64_t offset, int whence) {
62 CHECK_GE(fd_, 0);
63 return lseek64(fd_, offset, whence);
64}
65
Gilad Arnold11c066f2012-05-10 14:37:25 -070066bool EintrSafeFileDescriptor::Close() {
67 CHECK_GE(fd_, 0);
Mike Frysingerbcee2ca2014-05-14 16:28:23 -040068 if (IGNORE_EINTR(close(fd_)))
Gilad Arnold6eccc532012-05-17 15:44:22 -070069 return false;
70 Reset();
71 return true;
72}
73
74void EintrSafeFileDescriptor::Reset() {
75 fd_ = -1;
76}
77
Gilad Arnold11c066f2012-05-10 14:37:25 -070078} // namespace chromeos_update_engine