diff -r ef9237601f24 -r 6a6462ce8a08 librazor/razor.c --- a/librazor/razor.c Thu Oct 01 19:54:03 2009 +0100 +++ b/librazor/razor.c Thu Oct 01 20:02:12 2009 +0100 @@ -37,6 +37,9 @@ #include #include #include +#ifdef MSWIN_API +#include +#endif #include "razor-internal.h" #include "razor.h" @@ -93,6 +96,8 @@ empty = array_add(&set->string_pool, 1); *empty = '\0'; + set->lock_fd = -1; + return set; } @@ -138,6 +143,13 @@ return -1; } + if (set->mapped_files == NULL) { + for (i = 0; i < ARRAY_SIZE(razor_sections); i++) { + array = (void *) set + razor_sections[i].offset; + array_release(array); + } + } + file->next = set->mapped_files; set->mapped_files = file; @@ -167,6 +179,7 @@ struct razor_set *set; set = zalloc(sizeof *set); + set->lock_fd = -1; if (razor_set_bind_sections(set, filename)){ free(set); return NULL; @@ -174,6 +187,56 @@ return set; } +int +razor_set_aquire_lock(struct razor_set *set, const char *path, int exclusive) +{ + int fd; + assert(set != NULL); + + if (path) { + fd = open(path, O_CREAT | O_RDWR | O_TRUNC | O_BINARY, 0666); + if (fd < 0) + return -1; + } else { + fd = -1; + } + +#ifdef MSWIN_API + DWORD flags = LOCKFILE_FAIL_IMMEDIATELY; + OVERLAPPED lock = {0}; + + if (exclusive) + flags |= LOCKFILE_EXCLUSIVE_LOCK; + if (fd >= 0 && !LockFileEx(_get_osfhandle(fd), flags, 0, 1, 0, &lock)) { + close(fd); + return -1; + } + if (set->lock_fd >= 0) + (void)UnlockFile(_get_osfhandle(set->lock_fd), 0, 0, 1, 0); +#else + struct flock lock = {0}; + + lock.l_type = exclusive ? F_WRLCK : F_RDLCK; + lock.l_whence = SEEK_SET; + lock.l_start = 0; + lock.l_len = 0; + if (fd >= 0 && fcntl(fd, F_SETLK, &lock) < 0) { + close(fd); + return -1; + } + if (set->lock_fd >= 0) { + lock.l_type = F_UNLCK; + (void)fcntl(set->lock_fd, F_SETLK, &lock); + } +#endif + + if (set->lock_fd >= 0) + close(set->lock_fd); + set->lock_fd = fd; + + return 0; +} + RAZOR_EXPORT void razor_set_destroy(struct razor_set *set) { @@ -196,6 +259,7 @@ } } + razor_set_aquire_lock(set, NULL, 0); free(set); }