00001 /* vim: set sw=4 sts=4 et foldmethod=syntax : */ 00002 00003 /* 00004 * Copyright (c) 2006 Ciaran McCreesh 00005 * 00006 * This file is part of the Paludis package manager. Paludis is free software; 00007 * you can redistribute it and/or modify it under the terms of the GNU General 00008 * Public License version 2, as published by the Free Software Foundation. 00009 * 00010 * Paludis is distributed in the hope that it will be useful, but WITHOUT ANY 00011 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 00012 * FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 00013 * details. 00014 * 00015 * You should have received a copy of the GNU General Public License along with 00016 * this program; if not, write to the Free Software Foundation, Inc., 59 Temple 00017 * Place, Suite 330, Boston, MA 02111-1307 USA 00018 */ 00019 00020 #ifndef PALUDIS_GUARD_PALUDIS_FD_HOLDER_HH 00021 #define PALUDIS_GUARD_PALUDIS_FD_HOLDER_HH 1 00022 00023 #include <unistd.h> 00024 00025 namespace paludis 00026 { 00027 /** 00028 * RAII holder for a file descriptor. 00029 */ 00030 class PALUDIS_VISIBLE FDHolder 00031 { 00032 private: 00033 const int _fd; 00034 const bool _sync; 00035 00036 public: 00037 ///\name Basic operations 00038 ///\{ 00039 00040 FDHolder(const int fd, bool sync = true) : 00041 _fd(fd), 00042 _sync(sync) 00043 { 00044 } 00045 00046 ~FDHolder() 00047 { 00048 if (-1 != _fd) 00049 { 00050 if (_sync) 00051 ::fsync(_fd); 00052 ::close(_fd); 00053 } 00054 } 00055 00056 ///\} 00057 00058 /** 00059 * Fetch our file descriptor. 00060 */ 00061 operator int () const 00062 { 00063 return _fd; 00064 } 00065 }; 00066 } 00067 00068 #endif