Single Instance Lock
gxProcessLock lets one instance of a program run at a time (DataReel 7.4).
Overview
Acquire() takes an exclusive lock on a lock file (flock on POSIX, LockFileEx on Windows) and writes the holder's process id into it. A second Acquire() of the same file, in another process or this one, fails at once, and HolderPid() names the holder. The operating system drops the lock when the holder ends, however it ends, so a lock file left by a crash or kill -9 never blocks a restart: only a live holder does. The lock is not inherited by child processes. Network file systems without lock support are not supported.
gxProcessLock lk;
if(!lk.Acquire("/var/run/myapp.lock")) {
fprintf(stderr, "already running: %s\n", lk.Error().c_str()); // "... is locked by process 4711"
return 2;
}
// ... the work; the lock goes with the process, or lk.Release()
Functions
bool Acquire(const std::string &fname)Takes the lock (the file is made if needed). False if another holder has it (HolderPid()) or the file cannot be opened (Error()).
void Release() / bool Held() constGives the lock up; the file stays, emptied.
long long HolderPid() const / const std::string &Error() constThe holder's process id (this process after a successful Acquire()), and why Acquire() failed.
static bool IsLocked(const std::string &fname, long long *pid = 0)True if a live process holds the lock, without taking it.