为IPWorks做的一个HA方案,技术上打算用到锁文件,自己写了一个,参考了sourceforge上高手的代码。
似乎线程安全上还有点小问题,以后再考虑吧。
不过等到上到CBA了以后,HA由Core MW提供,就不需要了。
//
// Locking files
// LockFile.hh
//
#ifndef _MY_LOCKF_HH_
#define _MY_LOCKF_HH_
#include
extern "C" {
# include
# include
# include
# include
# include
# include
# include
};
#define LOCK_DIR "/var/lock"
class LockFile {
private:
bool isLocked;
string name;
public:
LockFile();
~LockFile();
bool Lock(const char *fname);
bool Lock(string fname)
{ Lock(fname.c_str()); }
void UnLock();
};
#endif
========================================================================================
//
// Implementation of lock for files
// LockFile.cc
//
#include "LockFile.hh"
LockFile::LockFile()
{
isLocked = false;
name = "";
}
LockFile::~LockFile()
{
UnLock();
}
bool LockFile::Lock(const char *fname)
{
FILE *fp;
const char *dn;
int n;
struct stat sbuf;
printf("Locking file %s\n", fname);
dn = fname;
if (dn = strrchr(fname, '/'))
dn++;
name = LOCK_DIR;
name += "/LCK..";
name += dn;
isLocked = false;
if (stat(name.c_str(), &sbuf) != -1) {
printf("Lock file exists.\n");
if ((fp = fopen(name.c_str(), "r")) != NULL) {
fscanf(fp, "%10d\n", &n);
fclose(fp);
if (n == getpid())
return true;
printf("Device %s locked by process %d\n", dn, n);
}
return isLocked;
}
printf("Creating file lock %s\n", name.c_str());
if ((fp = fopen(name.c_str(), "w")) == NULL)
printf("Creating lock file %s\n", name.c_str());
fprintf(fp, "%10d\n", getpid());
fclose(fp);
return isLocked = true;
}
void LockFile::UnLock()
{
printf("Unlocking %s\n", name.c_str());
if (isLocked) unlink(name.c_str());
}
阅读(1608) | 评论(0) | 转发(0) |