tizen beta release
[framework/web/wrt-commons.git] / modules / core / src / named_output_pipe.cpp
1 /*
2  * Copyright (c) 2011 Samsung Electronics Co., Ltd All Rights Reserved
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  */
16 /*
17  * @file        named_output_pipe.cpp
18  * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @version     1.0
20  * @brief       This file is the implementation file of named output pipe
21  */
22 #include <dpl/named_output_pipe.h>
23 #include <dpl/binary_queue.h>
24 #include <dpl/scoped_free.h>
25 #include <sys/types.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 #include <fcntl.h>
29 #include <errno.h>
30
31 namespace DPL
32 {
33 NamedOutputPipe::NamedOutputPipe()
34     : m_fifo(-1)
35 {
36 }
37
38 NamedOutputPipe::~NamedOutputPipe()
39 {
40     Close();
41 }
42
43 void NamedOutputPipe::Open(const std::string& pipeName)
44 {
45     // Then open it for reading or writing
46     int fifo = TEMP_FAILURE_RETRY(open(pipeName.c_str(), O_WRONLY | O_NONBLOCK));
47
48     if (fifo == -1)
49         ThrowMsg(Exception::OpenFailed, pipeName);
50
51     m_fifo = fifo;
52 }
53
54 void NamedOutputPipe::Close()
55 {
56     if (m_fifo == -1)
57         return;
58
59     if (TEMP_FAILURE_RETRY(close(m_fifo)) == -1)
60         Throw(Exception::CloseFailed);
61
62     m_fifo = -1;
63 }
64
65 size_t NamedOutputPipe::Write(const BinaryQueue &buffer, size_t bufferSize)
66 {
67     // Adjust write size
68     if (bufferSize > buffer.Size())
69         bufferSize = buffer.Size();
70
71     // FIXME: User write visitor to write !
72     // WriteVisitor visitor
73
74     ScopedFree<void> flattened(malloc(bufferSize));
75     buffer.Flatten(flattened.Get(), bufferSize);
76
77     ssize_t result = TEMP_FAILURE_RETRY(write(m_fifo, flattened.Get(), bufferSize));
78
79     if (result > 0)
80     {
81         // Successfuly written some bytes
82         return static_cast<size_t>(result);
83     }
84     else if (result == 0)
85     {
86         // This is abnormal result
87         ThrowMsg(CommonException::InternalError, "Invalid socket write result, 0 bytes written");
88     }
89     else
90     {
91         // Interpret error result
92         // FIXME: Handle errno
93         Throw(AbstractOutput::Exception::WriteFailed);
94     }
95 }
96
97 int NamedOutputPipe::WaitableWriteHandle() const
98 {
99     return m_fifo;
100 }
101 } // namespace DPL