lockf.c 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  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 <features.h>
  15. #include <sys/types.h>
  16. #include <fcntl.h>
  17. #include <unistd.h>
  18. #include <errno.h>
  19. #include <string.h>
  20. /* lockf is a simplified interface to fcntl's locking facilities. */
  21. int lockf (int fd, int cmd, off_t len)
  22. {
  23. struct flock fl;
  24. memset ((char *) &fl, '\0', sizeof (fl));
  25. /* lockf is always relative to the current file position. */
  26. fl.l_whence = SEEK_CUR;
  27. fl.l_start = 0;
  28. fl.l_len = len;
  29. switch (cmd)
  30. {
  31. case F_TEST:
  32. /* Test the lock: return 0 if FD is unlocked or locked by this process;
  33. return -1, set errno to EACCES, if another process holds the lock. */
  34. fl.l_type = F_RDLCK;
  35. if (fcntl (fd, F_GETLK, &fl) < 0)
  36. return -1;
  37. if (fl.l_type == F_UNLCK || fl.l_pid == getpid ())
  38. return 0;
  39. __set_errno(EACCES);
  40. return -1;
  41. case F_ULOCK:
  42. fl.l_type = F_UNLCK;
  43. cmd = F_SETLK;
  44. break;
  45. case F_LOCK:
  46. fl.l_type = F_WRLCK;
  47. cmd = F_SETLKW;
  48. break;
  49. case F_TLOCK:
  50. fl.l_type = F_WRLCK;
  51. cmd = F_SETLK;
  52. break;
  53. default:
  54. __set_errno(EINVAL);
  55. return -1;
  56. }
  57. return fcntl(fd, cmd, &fl);
  58. }
  59. libc_hidden_def(lockf)