Initialize Tizen 2.3
[framework/web/wrt-commons.git] / modules / 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/wrt_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                 WrtLogD("Failed to fsync scoped close error: %s",
46                     errString.c_str());
47             }
48
49             if (::close(handle) == -1) {
50                 std::string errString = GetErrnoString();
51                 WrtLogD("Failed to scoped close error: %s", errString.c_str());
52             }
53         }
54     }
55 };
56
57 class ScopedClose : public ScopedResource<ScopedClosePolicy>
58 {
59     typedef ScopedClosePolicy Policy;
60     typedef ScopedResource<Policy> BaseType;
61     typedef ScopedClosePolicy::Type Type;
62
63   public:
64     explicit ScopedClose(Type handle = Policy::NullValue()) :
65         BaseType(handle)
66     { }
67 };
68 } // namespace DPL
69
70 #endif // DPL_SCOPED_CLOSE_H