QLockFile Class
The QLockFile class provides locking between processes using a file. More...
| Header: | #include <QLockFile> |
| qmake: | QT += core |
| Since: | Qt 5.1 |
This class was introduced in Qt 5.1.
Public Types
| enum | LockError { NoError, LockFailedError, PermissionError, UnknownError } |
Detailed Description
A lock file can be used to prevent multiple processes from accessing concurrently the same resource. For instance, a configuration file on disk, or a socket, a port, a region of shared memory...
Serialization is only guaranteed if all processes that access the shared resource use QLockFile, with the same file path.
QLockFile supports two use cases: to protect a resource for a short-term operation (e.g. verifying if a configuration file has changed before saving new settings), and for long-lived protection of a resource (e.g. a document opened by a user in an editor) for an indefinite amount of time.
When protecting for a short-term operation, it is acceptable to call lock() and wait until any running operation finishes. When protecting a resource over a long time, however, the application should always call setStaleLockTime(0) and then tryLock() with a short timeout, in order to warn the user that the resource is locked.
If the process holding the lock crashes, the lock file stays on disk and can prevent any other process from accessing the shared resource, ever. For this reason, QLockFile tries to detect such a "stale" lock file, based on the process ID written into the file. To cover the situation that the process ID got reused meanwhile, the current process name is compared to the name of the process that corresponds to the process ID from the lock file. If the process names differ, the lock file is considered stale. Additionally, the last modification time of the lock file (30s by default, for the use case of a short-lived operation) is taken into account. If the lock file is found to be stale, it will be deleted.
For the use case of protecting a resource over a long time, you should therefore call setStaleLockTime(0), and when tryLock() returns LockFailedError, inform the user that the document is locked, possibly using getLockInfo() for more details.
Note: On Windows, this class has problems detecting a stale lock if the machine's hostname contains characters outside the US-ASCII character set.
Member Type Documentation
enum QLockFile::LockError
This enum describes the result of the last call to lock() or tryLock().
| Constant | Value | Description |
|---|---|---|
QLockFile::NoError | 0 | The lock was acquired successfully. |
QLockFile::LockFailedError | 1 | The lock could not be acquired because another process holds it. |
QLockFile::PermissionError | 2 | The lock file could not be created, for lack of permissions in the parent directory. |
QLockFile::UnknownError | 3 | Another error happened, for instance a full partition prevented writing out the lock file. |