2 * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 * @file file_input.cpp
18 * @author Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
20 * @brief This file is the implementation file of named input pipe
23 #include <dpl/file_input.h>
24 #include <dpl/binary_queue.h>
25 #include <dpl/log/log.h>
32 namespace // anonymous
34 const size_t DEFAULT_READ_BUFFER_SIZE = 4096;
35 } // namespace anonymous
37 FileInput::FileInput() :
41 FileInput::FileInput(const std::string& fileName) :
47 FileInput::~FileInput()
52 void FileInput::Open(const std::string& fileName)
55 int fd = TEMP_FAILURE_RETRY(open(fileName.c_str(), O_RDONLY | O_NONBLOCK));
57 // Throw an exception if an error occurred
59 ThrowMsg(Exception::OpenFailed, fileName);
62 // Close if any existing
65 // Save new descriptor
68 LogPedantic("Opened file: " << fileName);
71 void FileInput::Close()
77 if (TEMP_FAILURE_RETRY(close(m_fd)) == -1) {
78 Throw(Exception::CloseFailed);
83 LogPedantic("Closed file");
86 BinaryQueueAutoPtr FileInput::Read(size_t size)
88 size_t bytesToRead = size >
89 DEFAULT_READ_BUFFER_SIZE ? DEFAULT_READ_BUFFER_SIZE : size;
91 // Malloc default read buffer size
92 // It is unmanaged, so it can be then attached directly to binary queue
93 void *buffer = malloc(bytesToRead);
96 throw std::bad_alloc();
99 LogPedantic("Trying to read " << bytesToRead << " bytes");
101 ssize_t result = TEMP_FAILURE_RETRY(read(m_fd, buffer, bytesToRead));
103 LogPedantic("Read " << result << " bytes from file");
106 // Succedded to read socket data
107 BinaryQueueAutoPtr binaryQueue(new BinaryQueue());
109 // Append unmanaged memory
110 binaryQueue->AppendUnmanaged(buffer,
112 &BinaryQueue::BufferDeleterFree,
117 } else if (result == 0) {
118 // Socket was gracefuly closed
121 // Return empty buffer
122 return BinaryQueueAutoPtr(new BinaryQueue());
124 // Must first save errno value, because it may be altered
125 int lastErrno = errno;
130 // Interpret error result
133 // FIXME: Handle specific errno
134 Throw(AbstractInput::Exception::ReadFailed);
138 WaitableHandle FileInput::WaitableReadHandle() const
140 return static_cast<WaitableHandle>(m_fd);