24 #include <kcomponentdata.h>
27 #include <klocalizedstring.h>
28 #include <kstandarddirs.h>
30 #include <QtCore/QFile>
31 #include <QtCore/QTextStream>
35 #include <sys/types.h>
44 Private(
const QString &identifier )
45 : mIdentifier( identifier ),
46 mOrigIdentifier( identifier )
48 mIdentifier.replace( QLatin1Char(
'/' ), QLatin1Char(
'_' ) );
50 mIdentifier.replace( QLatin1Char(
':' ), QLatin1Char(
'_' ) );
55 QString mOrigIdentifier;
56 QString mLockUniqueName;
61 : d( new Private( identifier ) )
74 return KStandardDirs::locateLocal(
"data", QLatin1String(
"kabc/lock/" ) );
79 QFile file( filename );
80 if ( !file.open( QIODevice::ReadOnly ) ) {
84 QTextStream t( &file );
85 t >> pid >> ws >> app;
92 QFile file( filename );
93 if ( !file.open( QIODevice::WriteOnly ) ) {
97 QTextStream t( &file );
98 t << ::getpid() << endl << QString( KGlobal::mainComponent().componentName() );
105 return locksDir() + d->mIdentifier + QLatin1String(
".lock" );
111 kDebug() <<
"-- lock name:" << lockName;
113 if ( QFile::exists( lockName ) ) {
118 d->mError = i18n(
"Unable to open lock file." );
122 int retval = ::kill( pid, 0 );
123 if ( retval == -1 && errno == ESRCH ) {
124 QFile::remove( lockName );
125 kWarning() <<
"Removed stale lock file from process '" << app <<
"'";
127 d->mError = i18n(
"The resource '%1' is locked by application '%2'.",
128 d->mOrigIdentifier, app );
133 QString lockUniqueName;
134 lockUniqueName = d->mIdentifier + KRandom::randomString( 8 );
135 d->mLockUniqueName = KStandardDirs::locateLocal(
136 "data", QLatin1String(
"kabc/lock/" ) + lockUniqueName );
137 kDebug() <<
"-- lock unique name:" << d->mLockUniqueName;
143 int result = ::link( QFile::encodeName( d->mLockUniqueName ),
144 QFile::encodeName( lockName ) );
154 d->mError = i18n(
"Error" );
163 if ( pid == getpid() ) {
165 QFile::remove( d->mLockUniqueName );
168 d->mError = i18n(
"Unlock failed. Lock file is owned by other process: %1 (%2)", app, pid );
169 kDebug() << d->mError;
QString lockFileName() const
Returns the path of the lock file.
static bool writeLockFile(const QString &filename)
Writes the process ID and the application name to a lock file.
void unlocked()
Emitted after the lock has been unlocked.
static bool readLockFile(const QString &filename, int &pid, QString &app)
Reads the process ID and the application name from a lock file.
static QString locksDir()
Returns the path of the directory where locks are created.
Lock(const QString &identifier)
Constructor.
virtual bool unlock()
Unlock resource.
virtual bool lock()
Lock resource.
void locked()
Emitted after the lock has been locked.
virtual QString error() const
Returns the lastest error message.
~Lock()
Destruct lock object.