Skip to content

Instantly share code, notes, and snippets.

@mu578
Created March 20, 2022 00:38
Show Gist options
  • Save mu578/3b914c311e466b484ffb71b63663287b to your computer and use it in GitHub Desktop.
Save mu578/3b914c311e466b484ffb71b63663287b to your computer and use it in GitHub Desktop.
// flock_win32.h
# ifndef LOCK_SH
# define LOCK_SH 1
# define LOCK_EX 2
# define LOCK_NB 4
# define LOCK_UN 8
# endif
int __cdecl flock(int fd, int operation);
// flock_win32.c
# include <synchapi.h>
# include <fileapi.h>
# include <io.h>
# include <sys/locking.h>
# include <errno.h>
static HANDLE __g_flock_win32_mtx;
# define __flock_win32_lock() __g_flock_win32_mtx = CreateMutex(NULL, TRUE, NULL)
# define __flock_win32_unlock() ReleaseMutex(__g_flock_win32_mtx); CloseHandle(__g_flock_win32_mtx)
# define __flock_win32_fsize(fd) (long)GetFileSize(_get_osfhandle(fd))
int flock(int fd, int operation)
{
int ret = -1, op, lk;
__flock_win32_lock();
op = operation;
lk = 0;
if (op & LOCK_NB) {
op &= ~LOCK_NB;
}
switch (op)
{
case LOCK_EX:
lk = _LK_LOCK;
break;
case LOCK_SH:
lk = _LK_RLCK;
break;
case LOCK_UN:
lk = _LK_UNLCK;
break;
default:
__flock_win32_unlock();
return ret;
}
ret = _locking(fd, lk, __flock_win32_fsize(fd));
__flock_win32_unlock();
return ret;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment