Initialize Tizen 2.3
[framework/web/wrt-commons.git] / modules_mobile / core / include / dpl / scoped_close.h
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        scoped_close.h
18  * @author      Przemyslaw Dobrowolski (p.dobrowolsk@samsung.com)
19  * @version     1.0
20  * @brief       This file is the implementation file of scoped close RAII
21  */
22 #ifndef DPL_SCOPED_CLOSE_H
23 #define DPL_SCOPED_CLOSE_H
24
25 #include <unistd.h>
26 #include <cerrno>
27 #include <string>
28 #include <dpl/log/log.h>
29 #include <dpl/scoped_resource.h>
30 #include <dpl/errno_string.h>
31
32 namespace DPL {
33 struct ScopedClosePolicy
34 {
35     typedef int Type;
36     static Type NullValue()
37     {
38         return -1;
39     }
40     static void Destroy(Type handle)
41     {
42         if (handle != -1) {
43             if (TEMP_FAILURE_RETRY(::fsync(handle)) == -1) {
44                 std::string errString = GetErrnoString();
45                 LogPedantic("Failed to fsync scoped close error: "
46                             << errString);
47             }
48
49             if (::close(handle) == -1) {
50                 std::string errString = GetErrnoString();
51                 LogPedantic("Failed to scoped close error: "
52                             << errString);
53             }
54         }
55     }
56 };
57
58 class ScopedClose : public ScopedResource<ScopedClosePolicy>
59 {
60     typedef ScopedClosePolicy Policy;
61     typedef ScopedResource<Policy> BaseType;
62     typedef ScopedClosePolicy::Type Type;
63
64   public:
65     explicit ScopedClose(Type handle = Policy::NullValue()) :
66         BaseType(handle)
67     { }
68 };
69 } // namespace DPL
70
71 #endif // DPL_SCOPED_CLOSE_H