libkdegames Library API Documentation

kfilelock.cpp

00001 /* 00002 This file is part of the KDE games library 00003 Copyright (C) 2003 Nicolas Hadacek <hadacek@kde.org> 00004 00005 This library is free software; you can redistribute it and/or 00006 modify it under the terms of the GNU Library General Public 00007 License version 2 as published by the Free Software Foundation. 00008 00009 This library is distributed in the hope that it will be useful, 00010 but WITHOUT ANY WARRANTY; without even the implied warranty of 00011 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 00012 Library General Public License for more details. 00013 00014 You should have received a copy of the GNU Library General Public License 00015 along with this library; see the file COPYING.LIB. If not, write to 00016 the Free Software Foundation, Inc., 59 Temple Place - Suite 330, 00017 Boston, MA 02111-1307, USA. 00018 */ 00019 00020 #include "kfilelock.h" 00021 00022 #include <unistd.h> 00023 #include <sys/file.h> 00024 #include <errno.h> 00025 00026 #include <kdebug.h> 00027 00028 00029 KFileLock::KFileLock(int fd) 00030 : _fd(fd), _locked(false) 00031 {} 00032 00033 int KFileLock::lock() 00034 { 00035 kdDebug(11002) << "lock fd=" << _fd << endl; 00036 #ifdef F_SETLK 00037 # ifndef SEEK_SET 00038 # define SEEK_SET 0 00039 # endif 00040 struct flock lock_data; 00041 lock_data.l_type = F_WRLCK; 00042 lock_data.l_whence = SEEK_SET; 00043 lock_data.l_start = lock_data.l_len = 0; 00044 if ( fcntl(_fd, F_SETLK, &lock_data)==-1 ) { 00045 if ( errno==EAGAIN ) return -2; 00046 return -1; 00047 } 00048 #else 00049 # ifdef LOCK_EX 00050 if ( flock (_fd, LOCK_EX|LOCK_NB)==-1 ) { 00051 if ( errno==EWOULDBLOCK ) return -2; 00052 return -1; 00053 } 00054 # else 00055 if ( lockf(_fd, F_TLOCK, 0)==-1 ) { 00056 if ( errno==EACCES ) return -2; 00057 return -1; 00058 } 00059 # endif 00060 #endif 00061 _locked = true; 00062 return 0; 00063 } 00064 00065 KFileLock::~KFileLock() 00066 { 00067 unlock(); 00068 } 00069 00070 void KFileLock::unlock() 00071 { 00072 if ( !_locked ) return; 00073 kdDebug(11002) << "unlock" << endl; 00074 # ifdef F_SETLK 00075 struct flock lock_data; 00076 lock_data.l_type = F_UNLCK; 00077 lock_data.l_whence = SEEK_SET; 00078 lock_data.l_start = lock_data.l_len = 0; 00079 (void)fcntl(_fd, F_SETLK, &lock_data); 00080 # else 00081 # ifdef F_ULOCK 00082 lockf(_fd, F_ULOCK, 0); 00083 # else 00084 flock(_fd, LOCK_UN); 00085 # endif 00086 # endif 00087 _locked = false; 00088 }
KDE Logo
This file is part of the documentation for libkdegames Library Version 3.2.3.
Documentation copyright © 1996-2004 the KDE developers.
Generated on Wed Jul 28 14:18:46 2004 by doxygen 1.3.7 written by Dimitri van Heesch, © 1997-2003