24 #include <kcomponentdata.h>
27 #include <kstandarddirs.h>
29 #include <QtCore/QFile>
30 #include <QtCore/QTextStream>
34 #include <sys/types.h>
43 Private(
const QString &identifier )
44 : mIdentifier( identifier ),
45 mOrigIdentifier( identifier )
47 mIdentifier.replace( QLatin1Char(
'/' ), QLatin1Char(
'_' ) );
49 mIdentifier.replace( QLatin1Char(
':' ), QLatin1Char(
'_' ) );
54 QString mOrigIdentifier;
55 QString mLockUniqueName;
60 : d( new Private( identifier ) )
73 return KStandardDirs::locateLocal(
"data", QLatin1String(
"kabc/lock/" ) );
78 QFile file( filename );
79 if ( !file.open( QIODevice::ReadOnly ) ) {
83 QTextStream t( &file );
84 t >> pid >> ws >> app;
91 QFile file( filename );
92 if ( !file.open( QIODevice::WriteOnly ) ) {
96 QTextStream t( &file );
97 t << ::getpid() << endl << QString( KGlobal::mainComponent().componentName() );
104 return locksDir() + d->mIdentifier + QLatin1String(
".lock" );
110 kDebug() <<
"-- lock name:" << lockName;
112 if ( QFile::exists( lockName ) ) {
117 d->mError = i18n(
"Unable to open lock file." );
121 int retval = ::kill( pid, 0 );
122 if ( retval == -1 && errno == ESRCH ) {
123 QFile::remove( lockName );
124 kWarning() <<
"Removed stale lock file from process '" << app <<
"'";
126 d->mError = i18n(
"The resource '%1' is locked by application '%2'.",
127 d->mOrigIdentifier, app );
132 QString lockUniqueName;
133 lockUniqueName = d->mIdentifier + KRandom::randomString( 8 );
134 d->mLockUniqueName = KStandardDirs::locateLocal(
135 "data", QLatin1String(
"kabc/lock/" ) + lockUniqueName );
136 kDebug() <<
"-- lock unique name:" << d->mLockUniqueName;
142 int result = ::link( QFile::encodeName( d->mLockUniqueName ),
143 QFile::encodeName( lockName ) );
153 d->mError = i18n(
"Error" );
162 if ( pid == getpid() ) {
164 QFile::remove( d->mLockUniqueName );
167 d->mError = i18n(
"Unlock failed. Lock file is owned by other process: %1 (%2)", app, pid );
168 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.