#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
+#include <sys/file.h>
#include "tlog.h"
#include "tmalloc.h"
if ( readonly ) {
db->readonly=1;
- db->fd = open(file, O_RDONLY | O_SHLOCK);
+ db->fd = open(file, O_RDONLY);
+ if ( flock( db->fd, LOCK_SH ) < 0 ) {
+ tlog(TL_CRIT,"FDBOpen: flock failed: %s",strerror(errno));
+ close(db->fd);
+ return FDB_ERROR;
+ }
} else {
- db->fd = open(file, O_CREAT | O_RDWR | O_EXLOCK, 0666);
+ db->fd = open(file, O_CREAT | O_RDWR, 0666);
+ if ( flock( db->fd, LOCK_EX ) < 0 ) {
+ tlog(TL_CRIT,"FDBOpen: flock failed: %s",strerror(errno));
+ close(db->fd);
+ return FDB_ERROR;
+ }
}
if ( db->fd < 0 ) {
rc = read(db->fd, &header, sizeof(FDBHeader));
if ( rc<0 ) {
+ flock( db->fd, LOCK_UN );
close(db->fd);
tlog(TL_CRIT,"FDBOpen: read failed: %s", strerror(errno));
return FDB_ERROR;
} else if ( rc==0 ) {
memset(&header, 0, sizeof(FDBHeader));
} else if ( rc != sizeof(FDBHeader) ) {
+ flock( db->fd, LOCK_UN );
close(db->fd);
tlog(TL_CRIT,"FDBOpen: header fault: %d bytes only", rc);
return FDB_ERROR;
} else if ( header.isopened ) {
+ flock( db->fd, LOCK_UN );
close(db->fd);
tlog(TL_CRIT,"FDBOpen: file wasn't closed correctly");
return FDB_ERROR;
if ( lseek(db->fd, header.freespace, SEEK_SET)!=header.freespace ||
read( db->fd, db->space, header.lenfreespace ) != header.lenfreespace ) {
+ flock( db->fd, LOCK_UN );
close(db->fd);
tlog(TL_CRIT,"FDBOpen: free space read failed: %s", strerror(errno));
return FDB_ERROR;
if ( lseek(db->fd, 0, SEEK_SET)!=0 ||
write(db->fd, &header, sizeof(FDBHeader)) != sizeof(FDBHeader) ||
fsync(db->fd) ) {
+ flock( db->fd, LOCK_UN );
close(db->fd);
if ( db->space ) tfree( db->space );
tlog(TL_CRIT,"FDBOpen: can't modify header: %s", strerror(errno));
tlog(TL_CRIT|TL_EXIT,"FDBClose: header write failed: %s", strerror(errno));
}
+ flock( db->fd, LOCK_UN );
close(db->fd);
if ( db->space )