lockf64.c 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. /* Copyright (C) 1994, 1996, 1997, 1998, 2000 Free Software Foundation, Inc.
  2. This file is part of the GNU C Library.
  3. The GNU C Library is free software; you can redistribute it and/or
  4. modify it under the terms of the GNU Library General Public License as
  5. published by the Free Software Foundation; either version 2 of the
  6. License, or (at your option) any later version.
  7. The GNU C Library is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
  10. Library General Public License for more details.
  11. You should have received a copy of the GNU Library General Public
  12. License along with the GNU C Library; see the file COPYING.LIB. If not,
  13. see <http://www.gnu.org/licenses/>. */
  14. #include <_lfs_64.h>
  15. #include <sys/types.h>
  16. #include <unistd.h>
  17. #include <fcntl.h>
  18. #include <errno.h>
  19. #include <string.h>
  20. #include <sys/syscall.h>
  21. #ifdef __NR_fcntl64
  22. #define flock flock64
  23. #define fcntl fcntl64
  24. #undef F_GETLK
  25. #define F_GETLK F_GETLK64
  26. #undef F_SETLK
  27. #define F_SETLK F_SETLK64
  28. #else
  29. #endif
  30. /* lockf is a simplified interface to fcntl's locking facilities. */
  31. int lockf64 (int fd, int cmd, off64_t len64)
  32. {
  33. struct flock fl;
  34. off_t len = (off_t) len64;
  35. if (len64 != (off64_t) len)
  36. {
  37. /* We can't represent the length. */
  38. __set_errno(EOVERFLOW);
  39. return -1;
  40. }
  41. memset((char *) &fl, '\0', sizeof (fl));
  42. /* lockf is always relative to the current file position. */
  43. fl.l_whence = SEEK_CUR;
  44. fl.l_start = 0;
  45. fl.l_len = len;
  46. switch (cmd)
  47. {
  48. case F_TEST:
  49. /* Test the lock: return 0 if FD is unlocked or locked by this process;
  50. return -1, set errno to EACCES, if another process holds the lock. */
  51. fl.l_type = F_RDLCK;
  52. if (fcntl (fd, F_GETLK, &fl) < 0)
  53. return -1;
  54. if (fl.l_type == F_UNLCK || fl.l_pid == getpid ())
  55. return 0;
  56. __set_errno(EACCES);
  57. return -1;
  58. case F_ULOCK:
  59. fl.l_type = F_UNLCK;
  60. cmd = F_SETLK;
  61. break;
  62. case F_LOCK:
  63. fl.l_type = F_WRLCK;
  64. cmd = F_SETLKW;
  65. break;
  66. case F_TLOCK:
  67. fl.l_type = F_WRLCK;
  68. cmd = F_SETLK;
  69. break;
  70. default:
  71. __set_errno(EINVAL);
  72. return -1;
  73. }
  74. return fcntl(fd, cmd, &fl);
  75. }