Navigation Menu

Skip to content

Commit

Permalink
cache persistent: support opening from multi processes on Windows
Browse files Browse the repository at this point in the history
It will work...
  • Loading branch information
kou committed Apr 12, 2017
1 parent 9e7db43 commit bcc24d2
Show file tree
Hide file tree
Showing 2 changed files with 48 additions and 6 deletions.
50 changes: 44 additions & 6 deletions lib/file_lock.c
Expand Up @@ -20,16 +20,34 @@
#include "grn_ctx.h"

#include <sys/stat.h>
#include <sys/types.h>
#include <fcntl.h>

#ifdef WIN32
# include <io.h>
# include <share.h>
#else /* WIN32 */
# include <sys/types.h>
# include <fcntl.h>
#endif /* WIN32 */

#ifdef WIN32
# define GRN_FILE_LOCK_IS_INVALID(file_lock) \
((file_lock)->handle == INVALID_HANDLE_VALUE)
#else /* WIN32 */
# define GRN_FILE_LOCK_IS_INVALID(file_lock) \
((file_lock)->fd == -1)
#endif /* WIN32 */

void
grn_file_lock_init(grn_ctx *ctx,
grn_file_lock *file_lock,
const char *path)
{
file_lock->path = path;
#ifdef WIN32
file_lock->handle = INVALID_HANDLE_VALUE;
#else /* WIN32 */
file_lock->fd = -1;
#endif /* WIN32 */
}

grn_bool
Expand All @@ -46,14 +64,24 @@ grn_file_lock_acquire(grn_ctx *ctx,
}

for (i = 0; i < n_lock_tries; i++) {
#ifdef WIN32
file_lock->handle = CreateFile(file_lock->path,
GENERIC_READ | GENERIC_WRITE,
0,
NULL,
CREATE_ALWAYS,
FILE_ATTRIBUTE_NORMAL,
NULL);
#else /* WIN32 */
file_lock->fd = open(file_lock->path, O_CREAT | O_EXCL);
if (file_lock->fd != -1) {
#endif
if (!GRN_FILE_LOCK_IS_INVALID(file_lock)) {
break;
}
grn_nanosleep(GRN_LOCK_WAIT_TIME_NANOSECOND);
}

if (file_lock->fd == -1) {
if (GRN_FILE_LOCK_IS_INVALID(file_lock)) {
ERR(GRN_NO_LOCKS_AVAILABLE,
"%s failed to acquire lock: <%s>",
error_message_tag, file_lock->path);
Expand All @@ -66,18 +94,28 @@ grn_file_lock_acquire(grn_ctx *ctx,
void
grn_file_lock_release(grn_ctx *ctx, grn_file_lock *file_lock)
{
if (file_lock->fd == -1) {
if (GRN_FILE_LOCK_IS_INVALID(file_lock)) {
return;
}

#ifdef WIN32
CloseHandle(file_lock->handle);
DeleteFile(file_lock->path);

file_lock->handle = INVALID_HANDLE_VALUE;
#else /* WIN32 */
close(file_lock->fd);
unlink(file_lock->path);

file_lock->fd = -1;
#endif /* WIN32 */
file_lock->path = NULL;
}

void
grn_file_lock_fin(grn_ctx *ctx, grn_file_lock *file_lock)
{
if (file_lock->fd != -1) {
if (!GRN_FILE_LOCK_IS_INVALID(file_lock)) {
grn_file_lock_release(ctx, file_lock);
}
}
4 changes: 4 additions & 0 deletions lib/grn_file_lock.h
Expand Up @@ -26,7 +26,11 @@ extern "C" {

typedef struct {
const char *path;
#ifdef WIN32
HANDLE handle;
#else /* WIN32 */
int fd;
#endif /* WIN32 */
} grn_file_lock;

void grn_file_lock_init(grn_ctx *ctx,
Expand Down

0 comments on commit bcc24d2

Please sign in to comment.