-static int get_lock(const char *dbpath)
-{
- int lockfd;
- char lockpath[PATH_MAX];
- struct flock lock;
- struct stat st;
-
- if ( (strlen(dbpath) + strlen(LOCKFILENAME+1)) > (PATH_MAX - 1) ) {
- dbd_log( LOGSTD, ".AppleDB pathname too long");
- exit(EXIT_FAILURE);
- }
- strncpy(lockpath, dbpath, PATH_MAX - 1);
- strcat(lockpath, "/");
- strcat(lockpath, LOCKFILENAME);
-
- if ((lockfd = open(lockpath, O_RDWR | O_CREAT, 0644)) < 0) {
- dbd_log( LOGSTD, "Error opening lockfile: %s", strerror(errno));
- exit(EXIT_FAILURE);
- }
-
- if ((stat(dbpath, &st)) != 0) {
- dbd_log( LOGSTD, "Error statting lockfile: %s", strerror(errno));
- exit(EXIT_FAILURE);
- }
-
- if ((chown(lockpath, st.st_uid, st.st_gid)) != 0) {
- dbd_log( LOGSTD, "Error inheriting lockfile permissions: %s", strerror(errno));
- exit(EXIT_FAILURE);
- }
-
- lock.l_start = 0;
- lock.l_whence = SEEK_SET;
- lock.l_len = 0;
- lock.l_type = F_WRLCK;
-
- if (fcntl(lockfd, F_SETLK, &lock) < 0) {
- if (errno == EACCES || errno == EAGAIN) {
- if (exclusive) {
- dbd_log( LOGSTD, "Database is in use and exlusive was requested", strerror(errno));
- exit(EXIT_FAILURE);
- };
- } else {
- dbd_log( LOGSTD, "Error getting fcntl F_WRLCK on lockfile: %s", strerror(errno));
- exit(EXIT_FAILURE);
- }
- }
-
- return lockfd;
-}
-
-static void free_lock(int lockfd)
-{
- struct flock lock;
-
- lock.l_start = 0;
- lock.l_whence = SEEK_SET;
- lock.l_len = 0;
- lock.l_type = F_UNLCK;
- fcntl(lockfd, F_SETLK, &lock);
- close(lockfd);
-}
-