flock.cpp 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. #include "flock.h"
  2. #ifndef _unix_
  3. #include <util/generic/utility.h>
  4. #include "winint.h"
  5. #include <io.h>
  6. #include <errno.h>
  7. #ifdef __cplusplus
  8. extern "C" {
  9. #endif
  10. int flock(int fd, int op) {
  11. return Flock((HANDLE)_get_osfhandle(fd), op);
  12. }
  13. int Flock(void* hdl, int op) {
  14. errno = 0;
  15. if (hdl == INVALID_HANDLE_VALUE) {
  16. errno = EBADF;
  17. return -1;
  18. }
  19. DWORD low = 1, high = 0;
  20. OVERLAPPED io;
  21. Zero(io);
  22. UnlockFileEx(hdl, 0, low, high, &io);
  23. switch (op & ~LOCK_NB) {
  24. case LOCK_EX:
  25. case LOCK_SH: {
  26. auto mode = ((op & ~LOCK_NB) == LOCK_EX) ? LOCKFILE_EXCLUSIVE_LOCK : 0;
  27. if (op & LOCK_NB) {
  28. if (LockFileEx(hdl, mode | LOCKFILE_FAIL_IMMEDIATELY, 0, low, high, &io)) {
  29. return 0;
  30. } else if (GetLastError() == ERROR_LOCK_VIOLATION) {
  31. ClearLastSystemError();
  32. errno = EWOULDBLOCK;
  33. return -1;
  34. }
  35. } else {
  36. if (LockFileEx(hdl, mode, 0, low, high, &io)) {
  37. return 0;
  38. }
  39. }
  40. break;
  41. }
  42. case LOCK_UN:
  43. return 0;
  44. break;
  45. default:
  46. break;
  47. }
  48. errno = EINVAL;
  49. return -1;
  50. }
  51. int fsync(int fd) {
  52. return _commit(fd);
  53. }
  54. #ifdef __cplusplus
  55. }
  56. #endif
  57. #endif