Kinetic C/C++ Client
 All Classes Functions Variables Pages
reader_writer.cc
1 /*
2  * kinetic-cpp-client
3  * Copyright (C) 2014 Seagate Technology.
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18  *
19  */
20 
21 #include "kinetic/reader_writer.h"
22 
23 #include <errno.h>
24 #include <unistd.h>
25 
26 #include "glog/logging.h"
27 
28 namespace kinetic {
29 
30 ReaderWriter::ReaderWriter(int fd) : fd_(fd) {}
31 
32 bool ReaderWriter::Read(void *buf, size_t n, int* err) {
33  size_t bytes_read = 0;
34  while (bytes_read < n) {
35  int status = read(fd_, reinterpret_cast<char *>(buf) + bytes_read, n - bytes_read);
36  if (status == -1 && errno == EINTR) {
37  continue;
38  }
39  if (status < 0) {
40  *err = errno;
41  PLOG(WARNING) << "Failed to read from socket";
42  return false;
43  }
44  if (status == 0) {
45  LOG(WARNING) << "Failed to read from socket";
46  return false;
47  }
48  bytes_read += status;
49  }
50 
51  return true;
52 }
53 
54 bool ReaderWriter::Write(const void *buf, size_t n) {
55  size_t bytes_written = 0;
56  while (bytes_written < n) {
57  int status = write(fd_, reinterpret_cast<const char *>(buf) + bytes_written,
58  n - bytes_written);
59  if (status == -1 && errno == EINTR) {
60  continue;
61  }
62  if (status < 0) {
63  PLOG(WARNING) << "Failed to write to socket";
64  return false;
65  }
66  if (status == 0) {
67  LOG(WARNING) << "Failed to write to socket";
68  return false;
69  }
70  bytes_written += status;
71  }
72 
73  return true;
74 }
75 
76 } // namespace kinetic